getchar

"Be careful if you mix getchar and [scanf](scanf___20240531_0915_44.pd) in the same program, scanf has a tendency to leave behind characters that it has "peeked" at but not read, including the new-line character.
 Consider what happens if we try and read a number first, then a character"
printf("Enter an integer: ");
scanf("%f", &i);
printf("Enter a command: ");
command = getchar();
"The call of scanf will leave behind any characters that weren't consumed during the reading of `i`, including (but not limited to) the new-line character, `getchar` will fetch the first leftover character, which wasn't what we had in mind."

idioms

see page 140 of c_programming_a_modern_approach

while (getchar() != '\n') /* skips the rest of the line */
;
while ( (ch = getchar()) == ' ') /* skips blanks */
;

related

backlinks