Jacob Graham Jacob Graham - 1 month ago 14
C Question

Input validation: checking multiple values

The user has only two choices 'a' or 'b', if the users input is not 'a' or 'b' an error message should prompt them to enter only 'a' or 'b'.

I enter the letter 'a' and it bypasses the while loop.

when I enter 'b' it doesn't bypass the while loop?

Any suggestions on fixing this?

#include <stdio.h>
int main(void)
char c;

printf("enter a or b to make it out!\n");

//loop if answer is NOT a or b
while ((c = getchar() != 'a') && (c = getchar() != 'b'))
//let the user know there has been a problem!
printf("That value is invalid");
printf("\nPlease enter a or b:\n");

printf("You made it out!");
return 0;


Whenever you do a getchar() a _different_ character is read. So you should change the while loop as

while (((c = getchar()) != 'a') && (c != 'b'))

Otherwise whenever the condition c = getchar() != 'b' is checked, c will be \n.

What is more, you should get that \n out of the way. So you may add another getchar() in your while loop whose return value you do not need to use.