Should I use fgets
or formatted scanf
like scanf("%10s", foo)
.
Excepted that scanf
does not read blank characters, which can be solved and do more stuffs with scanset, then why I should use fgets
instead of scanf
?
Any help would be appreciated.
Edit
One more thing I want to ask is: even when we use fgets
what happen if user enter characters more than boundary (I mean a lot of characters), does it lead to buffer overflow? Then how to deal with it?
On most operating sytems, user input is, by default, line-based. One reason for this is to allow the user to press the backspace key to correct the input, before sending the input to the program.
For line-based user input, it is meaningful and intuitive for a program to read one line of input at a time. This is what the function fgets
does (provided that the buffer is large enough to store the entire line of input).
The function scanf
, on the other hand, normally does not read one line of input at a time. For example, when you use the %s
or %d
conversion format specifier with scanf
, it will not consume an entire line of input. Instead, it will only consume as much input as matches the conversion format specifier. This means that the newline character at the end of the line will normally not be consumed (which can easily lead to programming bugs). Also, scanf
called with the %d
conversion format specifier will consider input such as 6sldf23dsfh2
as valid input for the number 6
, but any further calls to scanf
with the same specifier will fail, unless you discard the remainder of the line from the input stream.
This behavior of scanf
is counter-intuitive, whereas the behavior of fgets
is intuitive, when dealing with line-based user input.
After using fgets
, you can use the function sscanf
on the string, for parsing the contents of an individual line. This will allow you to continue using scansets. Or you can parse the line by some other means. Either way, as long as you are using fgets
instead of scanf
for reading the input, you will be handling one line of input at a time, which is the natural and intuitive way to deal with line-based user input.
When we use
fgets
what happen if user enter characters more than boundary (I mean a lot of characters), does it lead to buffer overflow? Then how to deal with it?
If the user enters more characters than fit in the buffer as specified by the second fgets
function argument, then it will not overflow the buffer. Instead, it will only extract as many characters from the input stream as fit in the buffer. You can determine whether the entire line was read by checking whether the string contains a newline character '\n'
at the end.