I'm working on my code. If I use scanf instead fgets, It works but I want to use fgets. If I use fgets after I enter number of lines, I need to press enter. How can I fix this problem? Is this normal? I hope I can explain.
int main() {
FILE *myfile;
myfile = fopen("test.txt", "w");
int line_count;
printf("Enter number of line:");
scanf("%d", &line_count);
if (myfile == NULL) {
printf("Can't create!");
return 1;
}
char line[100];
for (int i = 0;i < line_count;i++) {
fgets(line, sizeof(line), stdin);
fprintf(myfile, "Line %d\n",i+1);
}
fclose(myfile);
return 0;
}
I tried use scanf instead fgets but i want to use fgets.
You need to read the new line character
'\n'that corresponds to the pressed key Enter before usingfgetsas for examplePay attention to that in general you need check that a call of
scanforfgetswas successful.