-2

(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.

B.M. Corwen
  • 205
  • 3
  • 10

2 Answers2

3

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.

chemdog95
  • 366
  • 4
  • 16
0
(c != '1') && (c != '2')

This will be the right condition.

Also int c; getchar() returns int.

In words your condition was while( c is not '1' OR c is not '2' ) keep looping.

For c='1' or c='2' one of the condition would be true. Making it loop again and again.

Btw the expression (a||b) would be true if these holds

a   b   a||b
--+---+-------
F   F     F
T   F     T
F   T     T
T   T     T         T:True F:False
user2736738
  • 30,591
  • 5
  • 42
  • 56