0
scanf and getchar
sometimes I see the code like this: scanf("%d",&n); getchar(); So the question is how this working,why put the getchar() below the scanf?
1 Réponse
+ 8
`getchar()` reads the next `character` from the standard input.
The reason for being there (after scanf()) is because when the user enters the number and hit the Enter key, the newline character ('\n') remains in the input buffer. Now imagine the user decides to get a character and store it in another variable immediately after the `scanf()` like so
int n;
char c;
scanf("%d",&n); // the user input + '\n' hand out to the input buffer
scanf("%c", &c); // program skips this line because buffer isn't empty and contains '\n' and it gets stored in `c`
In such cases, the user can either places a `getchar()` in between the two `scanf()` like this
scanf("%d",&n);
getchar();
scanf("%c", &c);
or place a space before the `%c` like so
scanf("%d",&n);
scanf(" %c", &c);