-
While loop question
This is just a portion of my code and I know everything else works properly, but I need the code to check and see if the user entered a valid input (either 'H', 'S', or 'C'). I want the program to loop until the user inputs a valid variable, but when the user initially puts in one of the variables the program just hangs. It works fine if the user enters an invalid answer (it loops until a valid answer is entered) but then hangs again. Any ideas? I'm thinking the while loop is the issue...how do I get it to work? Thanks.
Code:
while ( ( status = getchar() ) != 'H' || 'S' || 'C' )
{
switch ( status )
{
case 'H':
case 'h':
break;
case 'S':
case 's':
break;
case 'C':
case 'c':
break;
case '\n':
case '\t':
case ' ':
break;
default: /* Catches all characters that are not valid entries */
printf("Incorrect status value entered.\n");
printf("Enter a valid status value [H for hourly, S for salaried staff, or C for contractor]:\n");
}
}
-
What's wrong with this code?
Code:
int n = 5;
//do something if n is 5 or 3 or 1
if (n == 5 || 3 || 1)
{
...
}
gg
[EDIT]
Solution:
Code:
//do something if n is 5 or 3 or 1
if ((n == 5) || (n == 3) || (n == 1))
{
...
}
-
I tried doing that as well, but it still doesn't work, unless I am missing something obvious...Thanks.
Code:
while ( ( status = getchar() != 'H') || ( status = getchar() != 'S') || ( status = getchar() != 'C') )
{
...
}
-
Here's one way
Code:
#include <stdio.h>
int main(void)
{
int c;
int Invalid = 1;
while (Invalid && (c = getchar()) != EOF)
{
Invalid = 0;
switch (c)
{
case 'H': puts("H entered"); break;
case 'I': puts("I entered"); break;
case 'J': puts("J entered"); break;
default:
puts("Invalid! ");
Invalid = 1;
while ((c = getchar()) != '\n' && c != EOF); /* Flush input buffer */
break;
}
}
return(0);
}