ugliness in scanf(3)

Doug Gwyn <gwyn> gwyn at brl-tgr.ARPA
Tue May 14 11:54:51 AEST 1985


> Something I've tried about every year in the last decade but
> haven't got to work on any machine is the following :
> 
> main() {
>     char buf[64];
> 
>     printf("Gimme string -");
>     scanf("%s\n", buf);
>     ...

Try:
	#include <stdio.h>
	/*ARGSUSED*/
	main(argc, argv)
		char	*argv[];
	{
		char	buf[64];

		(void)printf("Gimme string -");
		(void)scanf("%[^\n]", buf);
		(void)getchar();	/* eat NL */
		...
	}

It is important not to begin or end the format string with whitespace,
since that causes ALL whitespace in the input stream at that point to
be skipped.  In particular, trying to consume the newline with the
format statement will cause you to have to type extra stuff before the
first line scan is considered complete, and leading whitespace on the
second line will be eaten.

By the way, what happens if someone types a very long line in response
to your prompt?  (This sort of thing caused some really bad security
loopholes in older UNIX systems.)  The safe way to input a line is
with fgets() (NOT gets()).



More information about the Comp.lang.c mailing list