Possible scanf bug?

Roy Johnson rjohnson at shell.com
Fri Feb 1 04:09:27 AEST 1991


In article <146 at thor.UUCP> scjones at thor.UUCP (Larry Jones) writes:
>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.

Except that it would return 1, for number of variables assigned, not
number of formats read.

--
======= !{sun,psuvax1,bcm,rice,decwrl,cs.utexas.edu}!shell!rjohnson =======
"If he exploded, all of Manhattan would be talking in high, squeaky voices
for months!"  "Cool." -- When I Was Short
Roy Johnson, Shell Development Company



More information about the Comp.lang.c mailing list