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;
}
}
1 0
1 1
1 2
1 3
1,0.
1,1.
1,2.
1,3.
1,0.
1,1.
1,2.
1,3.
1,3.
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);