+ 1
Why does fgets take from the previous line?
I encountered this problem in a separate situation, but I tried to replicate the problem in the inserted code. Try to run it outside of Code Playground if you can. Here we have a scanf taking an integer n. Then it asks for n strings using the fgets function. However, the first fgets seems to take the previous newline character (when we pressed enter after the previous scanf) as its input, so only the first n-1 strings are actually read. Why does this happen? If we replace the fgets with scanf, the problem goes away. Why is that? https://code.sololearn.com/clz8pbWMF1S5/?ref=app
2 Réponses
+ 2
Scanf reads Integer digits upto a space or non-integer encounters.. Then it stops reading further. Next all input if any, goes to fgets. And fgets starts reading upto a new line encounter..
So after scanf read pointer does not comes to next line automatically, it's it read all next to next input taking..
Check this :
3A
B
C
It reads properly..
Check this
3\n
A
B
C, => this is not read by, because already it read 3 inputs..
+ 1
That makes sense. Thanks everyone.