scanf and gets in C | Sololearn: Learn to code for FREE!
Neuer Kurs! Jeder Programmierer sollte generative KI lernen!
Kostenlose Lektion ausprobieren
+ 11

scanf and gets in C

what is the major effect of using scanf to get a string value and why gets and fgets are better off

11th Apr 2019, 9:40 AM
Ôť│AsterisKÔť│ - avatar
2 Antworten
+ 10
It's common we see people do scanf("%s", string_variable); but this is considered unsafe because we didn't specify maximum number of characters to be read in, causing more characters possibly be written into the buffer than the buffer size allowed. Although not entirely sure, I think it's pretty safe if we define the maximum number of characters to read into the buffer such as scanf("%49s", string_variable); assuming the buffer was allocated for 50 characters (minus one for string terminator). IIRC, from what I read, also in SoloLearn sometimes before, `gets` is highly discouraged for the same reason, it doesn't even support buffer size definition (or was it deprecated?). On the other hand, `fgets` is "smart" enough to know the buffer size. But there's one thing that's quite bothering (for me at least), that `fgets` includes the line feed character while writing in the buffer, so care need to be taken with that function, after function call, one would need to find the \n and replace it with \0. Hth, cmiiw
11th Apr 2019, 10:20 AM
+ 3
I have always preferred scanf to gets and fgets but it's good to know the drawbacks.
12th Apr 2019, 5:47 AM
Sonic - avatar