Question 12.18

I'm reading a number with scanf %d and then a string with gets(), but the compiler seems to be skipping the call to gets()!


scanf %d won't consume a trailing newline. If the input number is immediately followed by a newline, that newline will immediately satisfy the gets().

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.

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


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback