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.
fgetsreturns. What if there aren't at leastline_countnumber of lines in the file?scanf()without checking the return value. If the user enters something other than a number,line_countwill be uninitialized.scanfcall will just continue to swallow whitespace (including newlines) forever.scanfcall with a trailing space in the format string will never return unless the user inputs some non-space characters. The loop and thefgetscall will simply never happen unless there's non-space input that is terminated by an extra newline (for the terminal to send the input to the program). See e.g. What is the effect of trailing white space in a scanf() format string?