fgets() waiting input for file write

89 Views Asked by At

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.

2

There are 2 best solutions below

11
Vlad from Moscow On

You need to read the new line character '\n' that corresponds to the pressed key Enter before using fgets as for example

printf("Enter number of line:");
scanf("%d", &line_count);

int c ;
while ( ( c = getchar() ) != EOF && c != '\n' );

Pay attention to that in general you need check that a call of scanf or fgets was successful.

0
Aconcagua On

I personally would go with these few lines:

char line[128];
printf("Enter number of lines:");
if(!fgets(line, sizeof(line), stdin))
{
    // TODO: error handling!
}
else
{
    char* end;
    long line_count = strtol(line, &end, 10);
    // ...
}

Using fgets solves the problem with the trailing new-line, and you can use end to test if the input was valid at all (or partially at least):

  • end == line -> no conversion at all took place
  • *end != '\n' -> not the entire input has been parsed (you could additionally test for the remaining characters being whitespace only...)

Some special cases might not be covered yet, leaving that up to you.

In any case, if you accept the input as valid (I would not open the file until you determined that, by the way) you can go on for all the following lines with fgets as you intended/wished.