Using fgets is pretty simple. As a feature, you can test to see it the input contains a newline. If not, there are pending characters.
scanf is possible using a scanset. %99[^\n] will scan up to 99 characters that are not a newline. %*c will consume the newline. If the only character is a newline then the scanset will fail and scanf will return 0. If more than 99 characters are entered, %*c will consume a character that is not a newline. fgets does not have that problem.
#include <stdio.h>
int main ( void) {
char string[100] = "";
int result = 0;
printf ( "using fgets\nenter a blank line to stop\n");
do {
fgets ( string, sizeof string, stdin);
} while ( string[0] != '\n');
printf ( "using scanf\nenter a blank line to stop\n");
do {
result = scanf ( "%99[^\n]%*c", string);
} while ( result == 1);
return 0;
}
With ungetc, if scanf reads too many characters, the last character can be put back in the stream if it is not a newline.
char last = 0;
do {
result = scanf ( "%99[^\n]%c", string, &last);
if ( EOF == result) {
fprintf ( stderr, "scanf EOF\n");
return 0;
}
if ( '\n' != last) {
ungetc ( last, stdin);
}
} while ( result == 2);
scanf()if you want to be able to handle bad input with any reliability. Ifscanf()fails, you really don't know what state your input stream is in. When you do something likefgets()and then maybesscanf()to parse the string, at least then you know exactly where your input stream is even if the data is bad. If you're reading from something like a pipe (because the user redirected input with something likeyourProgram < inputDataFileyou can't seek back to a previous location to recover.