In the following snippet, after reading the int the '\n' remains in the stdin, and is read by second scanf.
Is scanf called on the enter, and then reads what is in the stdin, or is it called before typing happens?
What signals to scanf that the input is ready? For example if I type on my keyboard 12345, and scanf is reading an int, it can be read as 1, 12, 123 ... If the enter is the signal to read, why doesn't scanf clear that character from the stdin?
#include <stdio.h> int main() { int a; scanf( "%d", &a ); char b; scanf( "%c", &b ); printf( "%d %c", a, b ); return 0; }
bwill read the'\n'left by the entry ofa. To correct use" %c"as the format string where the leading whitespace in the format string will consume the whitespace ('\n'being whitesapace as isspace,tab, etc..) Always validate the return ofscanf(). The return is the number of successful conversions that take place. Soif (scanf ("%d", &a) == 1)you know a valid integer was provided. (validation with"%c"isn't needed except to check forEOF.)scanfdoesn't consume trailing whitespace. The comment above gives you the work around to consume it before the next conversion.aa'\n'is inserted in the input stream. If you fail to account for the newline -- your next attempted read will read the\n'. This is also the primary reason that you are encouraged to take all user input withfgets()an a sufficiently sized buffer and then parse any needed information from the buffer usingsscanf()instead.fgets()will consume the trailing'\n'