C question (regarding input)

Joined
Jul 8, 2001
Messages
610
Here's the situation: In a program that I'm writing I need to be inside of a loop that is getting input with scanf, and if the input meets certain criteria then the loop is stopped, and various things happen. However if invalid input is entered the loop just starts back at the beginning with the prompt again. The problem I'm encountering is that once I've read some kind of input that's invalid, and the loop begins again, it seems to already have something sitting in it's input buffer (I'm sure that isn't the right description, but I don't really know how all of this works) so what happens is it runs through the loop once and doesn't allow the user to enter new input, and then in loops again and then it will actually let you type. Essentially the only problem this seems to be causing is cosmetic, but still I'd like to get to the bottom of it.

Because I'm certain that explaination was completely incomprehensible, this is what happens:

PROMPT: < I enter bad input >
PROMPT:
PROMPT:

The code is basically just:

while (input is not satisfactory)
{
scanf("type",&var) ;
}

Anyway, if anyone can make heads or tails of what I'm saying and has any idea how it might be remedied please let me know. Thanks.
 
hmm apparently reading my input character with scanf("%c%*c",&var) did the trick. It was leaving the newline in the input buffer and then reading that as input the next time around. Or something. Sorry to waste anyone's time, however if anyone reading this understands what all is actually happening here and feels like taking the time to explain it to me in detail, that would be appreciated.
 
You got the idea correct. When you type the character and hit enter, your program receives both the character and the newline character.

Let me know if you want/need more info.
 
Back
Top