I am currently learning how to write to txt file in c. I encountered a problem where the first column of text won't output the string it has been given.
#include <stdio.h>
#include <string.h>
int main() {
FILE * fptr;
//open file
fptr = fopen("test.txt", "a");
//entering how many lines will be used
int columns;
scanf("%d", &columns);
//loop for writing in lines
for (int i = 0; i < columns; i++) {
char temp_text[10001];
fgets (temp_text, 10000, stdin);
//to remove the \n caused by fgets
temp_text[strlen(temp_text) - 1] = '\0';
//fprintf is compatible with placeholders
fprintf (fptr, "data %d: %s\n", i, temp_text);
}
//closing file
fclose (fptr);
return 0;
}
The inputs are:
5
qw
er
ty
ui
I expected it to ask for n (in this case 5) time/s, instead it always asks for one less. The txt file shows:
data 0:
data 1: qw
data 2: er
data 3: ty
data 4: ui
A shown, it always skips putting the given string on the first line as well.
Thank you in advance.