[Courses] [C] whats wrong with scanf?

Peter Clay pete at flatline.org.uk
Sat Nov 9 19:54:10 EST 2002


On Fri, 8 Nov 2002, Morgon Kanter wrote:

> I never heard what exactly was wrong with using scanf() instead of fgets() 
> and sscanf(). Can someone explain this to me? please? =)

If you use scanf(), then all leading whitespace including newlines will be
ignored. So, a user who gets a prompt has to enter *something* before they
can get past it - hitting enter will do nothing.

The other reason is that scanf() only ever gives you one chance to look at
the data. If it doesn't match the input expression, you've lost it
forever. Worse, there may be input waiting but unprocessed, which will
confuse the next scanf() you do. There's no easy portable way to tell
whether input is waiting.

scanf() is really a relic of the punched-card era, where everything ran
noninteractively and aborting an entire job for a single input error was
acceptable behaviour.

Pete
-- 
Peter Clay                                         | Campaign for   _  _| .__
                                                   | Digital       /  / | |
                                                   | Rights!       \_ \_| |
                                                   | http://uk.eurorights.org




More information about the Courses mailing list