Search code examples
cstdinfgets

Issue with fgets while loop


At the moment I have something like this:

while(fgets(i, sizeof(i), stdin)!=NULL) {
    printf("%s", i);
    printf("line%d - j", j);
    j++

Which produces something like:

line1
line1 - j
line2
line2 - j
line3line3 - j

The problem I have is that the final line that I grab does not produce a new line and the second print statement continues to print on the same line.

Does somebody know how to fix this so that it produces:

line1
line1 - j
line2
line2 - j
line3
line3 - j

Solution

  • Fixed by adding a check if there's a new line at the end of the string:

    if (strchr (line, '\n') != NULL) { 
        printf("%s", line); 
    } 
    else { 
        printf("%s\n", line);
    }
    

    There's also the much shorter version suggested by Mr Lister:

    printf(strchr(line, '\n') ?"%s" :"%s\n", line);