Reputation: 187
So I'm writing a part of a program in c where I need the user to enter a character (A, B, or C). If they enter it in lowercase, enter more than one character, or if they enter a space or a letter outside of the above, it should output "Answer is invalid. Please try again." until they enter a valid answer.
I've ran into a problem where it outputs that error message for EACH character they enter in a single line. So say if they entered "asdas" it would output the error message five times. Is there a way to make sure the error message only gets outputted one time? I was thinking of making the program read only the first character in a sentence entered but I'm not sure.
I should also mention that a requirement of this task is that the getAnswer() function returns a character.
char getAnswer(){
char usersAnswer;
while(1){
printf("Enter your answer (A, B, C): \n");
scanf("%c", &usersAnswer);
if(checkAnswer(usersAnswer)){
return usersAnswer;
return 0;
}else{
printf("Answer is invalid. Please try again. \n");
}
}
}
Upvotes: 0
Views: 60
Reputation: 3613
The reason its getting outputted multiple times is because scanf is trying to read data from the input stream. And you're only storing input in one character thuse leaving all other characters still in the stream. Therefor scanf is just pulling from the stream any time data is available as apposed to blocking and waiting for more input. You have to clear your input stream each time you take in input.
Before your if(checkAnswer(usersAnswer))
statement, insert this line
int c = 0;
while(c!='\n' && c!=EOF)
c = getchar();
And that should clear your input stream.
Upvotes: 1