Search code examples
cfor-loopio

C language programs about input / output do not run properly


I am a newcomer to programming. My English is bad so I used google translate to ask this question:

I'm practicing using input/output in C language. I wrote a C program that takes a file called sample.txt and writes a few lines of words in it. I feel that the program that I made is correct but I found an error when compiling the program.

#include <stdio.h>

int main(){
    FILE *fptr;
    int n,I;
    char text[100];

    fptr=fopen("sample.txt","w");

    printf("Number of line? ");
    scanf("%d",&n);
    printf("\n");

    for( i = 1; i <= n; i++){
        printf("Line %d: ", I);
        fgets(text, sizeof(text), stdin);
        fputs(text, fptr);
    }
    fclose(fptr);

    return 0;
}

This is the output : enter image description here. enter image description here

Why line 1 and 2 are not separate like the others? I've checked several times and I don't know what went wrong.


Solution

  • As already pointed out by people in comments, you need to handle the newline left by scanf so that it doesn't get consumed by fgets() afterwards. You can either add a getchar() after scanf to handle this:

    printf("Number of line? ");
    scanf("%d",&n);
    getchar();
    

    Or you can replace usage of scanf for taking input with fgets() followed by a sscanf:

    char input[10];
    
    ...
    
    fgets(input, 10, stdin);
    sscanf(input, "%d", &n);
    

    When I made this changes, I was able to see desired output:

    c-posts : $ ./a.out 
    Number of line? 3
    Line 1: Foo
    Line 2: Bar
    Line 3: Pong
    c-posts : $ cat sample.txt 
    Foo
    Bar
    Pong