Search code examples
cvalidationinputwhile-loopgetchar

C - Why does this loop repeat, even when the right input is given to break it, using getchar()?


(New to C and programming in general.)

When I run this small program to prompt a user to enter 1 or 2, I want to check if the input is correct, so I ran a while loop that was supposed to run until the correct input is given. But even when I type 1 or 2 (doesn't matter whether it's from the beginning or after giving invalid input), the error message keeps printing.

Am I supposed to have a break in the while loop? If so, is there a more efficient/"less code" way of checking user input?

int main(void) {

char c;

printf("Press '1' or Press '2': ");
c = getchar();
while ((c != '1') || (c != '2')) {
    printf("ERROR: Invalid Input. Please try again: ");
    c = getchar();
}

return 0;
}

Thanks in advance.


Solution

  • You need to use && instead of ||. Think: if I enter 1, then (1 != 1) is false, but (1 != 2) is true, then (false || true) == true. Using && should fix your problem.