-
Endless fgets()
Hello!
My fgets function never stops, although I set the limit to the string length that is excepted.
Code:
char string[100];
...
case 1: {
//scanf(" %s",string);
while (getchar() != '\n') {
getchar();
}
fgets(string, 99,stdin);
printf("\n");
...
}
I am trying to replace the commented scanf with the same thing but that would allow spaces.
I have never been using fgets, but I have read that it stops when sees the newline or end of file(not this case).
Can anyone suggest what could be the problem?
Thank you!
-
I would suggest that the problem is not fgets, but what comes before fgets:
Code:
while (getchar() != '\n') {
getchar();
}
My guess is that you wrote this to remove anything left on the previous line of input, including the ending newline. Trouble is, if there is an odd number of characters remaining before that ending newline, this will consume them, and then wait for one more character of input. So if you then have input that you expect to be read by fgets, this loop will then read that input too, and keep reading all the way until the newline... and if there is an odd number of characters before that ending newline, it will then wait for one more character of input, so your fgets call doesn't get run, or if it does get run, it waits for input, thereby looking like it "never stops".
What you could do instead is this:
Code:
while (getchar() != '\n');
making the assumption that you won't encounter end-of-file (which can be triggered manually or perhaps the input is piped from file), but it may be better to consistently stick with fgets throughout, and use sscanf when you need scanf-style parsing.