+ 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

9th Jun 2021, 6:45 AM
Rishi
Rishi - avatar
7 Réponses
+ 2
Can you please show me your code for better understanding
9th Jun 2021, 6:52 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 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 """
9th Jun 2021, 7:59 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 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
9th Jun 2021, 8:03 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 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.
9th Jun 2021, 8:05 AM
🌀 Shail Murtaza شعیل مرتضیٰ
🌀 Shail Murtaza شعیل مرتضیٰ - avatar
+ 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
9th Jun 2021, 7:11 AM
Rishi
Rishi - avatar
+ 1
🌀 Shail Murtaza شعیل مرتضیٰ oh thank you so much. I got it now. Have a nice evening🤗
9th Jun 2021, 12:34 PM
Rishi
Rishi - avatar