+ 1
Question in C file operating
When getting inputs for lines for a text file using C, for example if the number of lines is n, we have to iterate from i=0 to i=n+1. My doubt is the why don't we use i=n instead of i=n+1? Thank you already 🤗 https://code.sololearn.com/cH0AOhjVSTWf/?ref=app
7 ответов
+ 2
Can you please show me your code for better understanding
+ 2
Rishi
Thanks for correcting me
Now I got your point.
After giving int input to scanf your "Enter" it means '\n' is still in the input buffer which is being read by fgets.
That's why your writing file also is not Correct.
after giving input
2
1st line
2nd line
Your file contains
"""
{Extra line}
1st line
2nd line
"""
+ 2
First fgets read that new line("\n") entered by you while inputting (number of lines)
Then it reads your input. That's why you are using n+1. That +1 is reading new line character
+ 2
You need to flush the input buffer to get correct input.
Flushing will remove '\n' from input buffer.
To do that use this line of code after scanf()
fflush(stdin);
Or you can use fgets before for loop and don't store that input in file.
+ 1
🌀 Shail Murtaza شعیل مرتضیٰ no it will iterate 3 times for "2" as input. First i=0, then i=1 and finally for i=2. To input 2 lines, I thought only two iterations is enough but for some reason it's not enough, it needs three iterations for fgets function to store 2 sentences in my file
+ 1
🌀 Shail Murtaza شعیل مرتضیٰ oh thank you so much. I got it now. Have a nice evening🤗