The problem:
After typing yEnter in response to your prompt, the input stream for your program contains the characters 'y'
and '\n'
(the newline character). The scanf
call removes the 'y'
character from the input stream, leaving the newline character in place.
gets
reads from the input stream until it sees a newline character, which it discards; since the first thing it sees is the newline character from the previous entry, it returns without reading any further input.
The solution:
First, don't use gets
. Ever. It was deprecated in the 1999 revision and has been removed completely from the 2011 revision. Using it will introduce a point of failure/security hole in your program. Replace that with a call to fgets
instead, just be aware that fgets
will try to store the newline in the target buffer if there's room.
Second, you need to consume that trailing newline from the input stream. The answer given by vish4071 shows one approach - use scanf
to read the character following your input (which should be the newline) and discard it:
scanf( " %c%*c", &i );
The leading blank in the format string tells scanf
to skip any leading whitespace, the %c
conversion specifier tells scanf
to read the next character from the input stream and store its value into i
, and the %*c
conversion specifier tells scanf
to read the next character from the input stream and discard it.
Another option is to consume input until you see a newline:
scanf( " %c", &i );
while ( getchar() != '\n' ) // repeatedly read characters from input stream
; // until we see a newline
Yet another option is to read your input as another string:
char answer[3]; // space for y/n response plus newline plus 0 terminator
...
if ( fgets( answer, sizeof answer, stdin ) )
{
if ( tolower( answer[0] ) == 'y' )
{
// do stuff
}
}
You will probably want to check for the presence of the newline character in the answer
buffer; if it isn't there, then the user typed in more characters than your buffer was sized to hold, which will likely foul up a future read, and you need to clear that spurious input before your next read operation:
if ( !strchr( answer, '\n' ) )
while ( getchar() != '\n' )
;