dshawn dshawn - 6 months ago 56
C Question

Loop going on longer than intended checking for empty line

I have a loop that is stopped once a flag is set to 1.

scanf("%d", &next);
scanf("%d", &next1);
int done=0,next,next1;
while (done==0) {
printf("%d,%d.",next,next1);
if (getchar()=='\n') {
scanf("%d", &next);
scanf("%d", &next1);
}
//if not, set flag and stop looping
else{
done=1;
}
}


It scans for 2 numbers from every line of input every loop until there are no more lines of the input left. I thought this would work fine but I encountered a problem when I tested out the following input:

1 0
1 1
1 2
1 3


The output should be

1,0.
1,1.
1,2.
1,3.


but instead it prints the last loop twice like this:

1,0.
1,1.
1,2.
1,3.
1,3.


Why does this scan the last line twice before terminating? is there a character I can check for so it ends after it prints the first "1,3."?

Answer Source

scanf() -

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

So, when the no more lines of the input left, the scanf() returns EOF and the while loop iterate because done is not set to 1 yet and printf() prints the value stored in next and next1 one more time. That's why the last entered value printed twice. After this the condition if (getchar()=='\n') fails and done set to 1 and while loop exits.

You can do:

int done=0,next,next1;
while (done==0) {
    if (scanf("%d%d", &next, &next1) != EOF)
        printf("%d,%d.",next,next1);
    else
        done=1;
}

Or

while (scanf("%d%d", &next, &next1) != EOF)
    printf("%d,%d.",next,next1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download