Space is the separator for the 5y3% s format specifier, and the new line is treated as a space, so it remains buffered. The console input is usually line-oriented, so a subsequent call to getchar () will immediately return because the "line" remains buffered.
scanf("%s", command ); while( getchar() != '\n' ){ }
Similarly, if you use getchar () or% c to get a single character, you usually need to clear the string, but in this case the character entered may be a new line, so you need a slightly different solution:
scanf("%c", ch ); while( ch != '\n' && getchar() != '\n' ){ }
similarly for getchar ():
ch = getchar(); while( ch != '\n' && getchar() != '\n' ){ }
Of course, the smart thing is to turn these solutions into standalone specialized input functions that you can reuse, and also use as a place to put common input validation and error checking code (as in the answer of Daniel Fisher, who reasonably validates for EOF - you would usually like to avoid duplication of these checks and error handling around the world).
Clifford
source share