0

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.

17
  • 2
    You need to check what fgets returns. What if there aren't at least line_count number of lines in the file? Commented Jun 12, 2023 at 12:36
  • 1
    Also, the order of things is a little wrong I think. If the file can't be opened, there's no need to ask the user about the number of lines to read. Commented Jun 12, 2023 at 12:37
  • 3
    Never ever use scanf() without checking the return value. If the user enters something other than a number, line_count will be uninitialized. Commented Jun 12, 2023 at 12:55
  • 3
    @yvs2014 Terrible advice. That requires that the user input something that isn't a newline or other whitepsace after the newline. Otherwise the scanf call will just continue to swallow whitespace (including newlines) forever. Commented Jun 12, 2023 at 13:20
  • 3
    @yvs2014 The scanf call with a trailing space in the format string will never return unless the user inputs some non-space characters. The loop and the fgets call 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? Commented Jun 12, 2023 at 13:32

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

11 Comments

That loop can be a little dangerous. What if there's an error and getchar returns EOF?
@Someprogrammerdude I wrote that he need to check the success of the previous call of scanf.
I added your loop but I still having problem.
@Alpiinoo What problem do you have?
@VladfromMoscow Checking the return of scanf is not enough, the error could come after the numeric input.
|
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.