Why doesn't getchar() wait for me to press enter after scanf()?

Your scanf only ate the number but not the trailing newline. Putting a newline or white space after the %d will then give you the opposite problem, reading too far.

This is why people don't like scanf.

I would suggest reading an actual line (use fgets(3)) and then using sscanf() to scan the string.


First of all, do not use fflush() to clear an input stream; the behavior is undefined:

7.19.5.2.2 If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

The problem is that the trailing newline is not being consumed by the "%d" conversion specifier, so it's being picked up immediately by the getchar(). There's no one best way to deal with this, but generally the approach is to read the whole line as text (using either fgets() or scanf() with a sized "%s" conversion specifier), which will consume the newline, then convert to the target data type using sscanf() or strtol() or strtod().