Possible scanf bug?
Larry Jones
scjones at thor.UUCP
Thu Jan 31 09:03:02 AEST 1991
In article <16134 at sdcc6.ucsd.edu>, cs163wcr at sdcc10.ucsd.edu (C Code. C Code run.) writes:
> char buffer[100]; /* Line won't be over 80, but so what */
> scanf ("%[^\n]%*c",buffer);
>
> If it reads an empty line, buffer isn't changed at all! It should
> make buffer the null string! Right?
Wrong. The %[ format specifier requires at least one character to
match in order to be considered successful. When you try to read
an empty line with it, it's just like trying to read "a" with a %d.
If you had checked the return value from scanf, it should have returned
0 (indicating that there were NO items read) as opposed to the usual
(for your format) 2. You should probably be using gets (which suffers
from the same problem as your scanf -- there's no check to make sure
you don't overflow the buffer) or fgets instead.
----
Larry Jones, SDRC, 2000 Eastman Dr., Milford, OH 45150-2789 513-576-2070
Domain: scjones at thor.UUCP Path: uunet!sdrc!thor!scjones
My brain is trying to kill me. -- Calvin
More information about the Comp.lang.c
mailing list