This problem has been noted before, but was closed due to what I saw as a
misinterpretation. The demo program had a flaw in the use of scanf, however did
display the bug that I am now faced with. The report I am referring to is
000237 "scanf does not work properly in a do while loop" posted by
<rogerh40@aa.net> on 07/11/1998 05:54:04, against versoin 2.01. The following
program was used in testing the problem, and alleviates the bug in the
presented program in report 000237.
/* Start : test.c */
#include <stdio.h>
#include <string.h>
int main (void) {
char input [80];
int done = 0;
while (! done) {
scanf ("%79[^\n]", input);
printf ("Input: %s\n", input);
if (! strcmp (input, "QUIT"))
done = 1;
}
return (0);
}
/* End : test.c */
Compiled with: gcc -o test.exe test.c
I don't claim to know scanf all that well. However, in all the cases that I
have used ?scanf, it has accepted %[\^n] or %[\^n]s (with or without the width
value) to denote reading a string until a \n (newline) is reached (or when
included, the width is exceeded). Under this instance, however, as soon as the
enter key is pressed in the above example (regardless of input; although I have
not had time to attempt every possible permutation), the loop will repeatedly
pass the first entry to any successive calls to scanf, causing it to ignore any
new input (this does occur outside loops as well).
For the record, the Borland compiles Turbo C 3.0 and Borland C 4.5 did not have
this problem, so this is being made with that limited reference. The scanf
documentation also seems to support the operation I received under the above
mentioned compilers.
Hopefully a solution (either to my use or to any bug that may exist) can be
presented.
Regards,
- Solaryn
This is not a bug, but a required behavior of the "%[...]" format
conversion: characters which don't match the set of expected characters
are left in the buffer. In this case, a newline doesn't match, and so
is pushed back onto the input, thereby triggering an infinite loop.
To produce the desired behavior, either consume the newline with
getc(stdin) or change the format string to "%79[^\n]%*1[\n]".
The test program above was tested with Turbo C 2.0 and with libc
from Irix and Linux machines, and behaved exactly like the
DJGPP-compiled one.
So I'm closing this report.