prev up next   top/contents search

comp.lang.c FAQ list · Question 12.18a

Q: I'm reading a number with scanf and %d, and then a string with gets():

	int n;
	char str[80];

	printf("enter a number: ");
	scanf("%d", &n);
	printf("enter a string: ");
	printf("you typed %d and \"%s\"\n", n, str);
but the compiler seems to be skipping the call to gets()!

A: If, in response to the above program, you type the two lines

	a string
scanf will read the 42, but not the newline following it. That newline will remain on the input stream, where it will immediately satisfy gets() (which will therefore seem to read a blank line). The second line, ``a string'', will not be read at all.

If you had happened to type both the number and the string on the same line:

	42 a string
the code would have worked more or less as you expected.

As a general rule, you shouldn't try to interlace calls to scanf with calls to gets() (or any other input routines); scanf's peculiar treatment of newlines almost always leads to trouble. Either use scanf to read everything or nothing.

See also questions 12.20 and 12.23.

Additional links: longer explanation

References: ISO Sec.
H&S Sec. 15.8 pp. 357-64

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North