fgetc(stdin) in a loop is producing strange behaviour

Terminals tend to be line-buffered, meaning that stream contents are accessible on a line-by-line basis.

So, when fgetc starts reading from STDIN, it’s reading a full line, which includes the newline character that ended that line. That’s the second character you’re reading.

As for fflush, that’s for flushing output buffers, not input buffers.

So, what you want to do here is to purge the input buffer by reading from it until its empty, or just explicitly ignore newline characters.

Leave a Comment