So what happens is that I have to press enter twice now. Why is this happening, and how can I fix this?
Well, that is what your code is doing - it first reads char-by-char until it finds newline. Then it calls fgets()
which will... well, read until it finds a newline (probably char-by-char, but, also possibly in some other way).
You could try fflush(stdin)
, but that is not guaranteed to do what you want (it only gives guarantees for output buffers, not for input).
Also, you may try setbuf(stdin, NULL)
which should disable buffering on standard input, so there would be nothing to flush. I tried this a few times on different systems and it worked, but documentation for this function is not 100% clear on this.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…