R
Rob
I'm stuck in a program I'm making. I'm supposed to have a menu that
asks the user to choose an option between 1 and 3. If the user chooses
a valid option, i.e. types a number from 1 to 3, then appropriate
things happen for the option they chose. After each option is
executed, the menu should come back asking them to choose an option
again. It should loop and do this forever. My problem is, I have to
detect the user entering anything other than the integers 1, 2 and 3,
and it's not working.
My program isn't handling invalid input correctly. If the user enters
"1abc", then it treats that as if they had just entered the number 1,
which is incorrect. If they enter valid input of 1, 2 or 3, then it
works. If they enter a string such as "abc" as input, then I get an
infinite loop where my menu is printed over and over. I'm not sure how
to fix this. Here's my code so far. Thanks for any help.
int option;
while (1) {
printf("choose an option [1-3]: ");
scanf("%d", &option);
if (option != 1 || option != 2 || option != 3) {
printf("\nInvalid option.\n");
} else if (option == 1) {
/* do something */
} else if (option == 2) {
/* do something */
} else if (option == 3) {
/* do something */
}
}
asks the user to choose an option between 1 and 3. If the user chooses
a valid option, i.e. types a number from 1 to 3, then appropriate
things happen for the option they chose. After each option is
executed, the menu should come back asking them to choose an option
again. It should loop and do this forever. My problem is, I have to
detect the user entering anything other than the integers 1, 2 and 3,
and it's not working.
My program isn't handling invalid input correctly. If the user enters
"1abc", then it treats that as if they had just entered the number 1,
which is incorrect. If they enter valid input of 1, 2 or 3, then it
works. If they enter a string such as "abc" as input, then I get an
infinite loop where my menu is printed over and over. I'm not sure how
to fix this. Here's my code so far. Thanks for any help.
int option;
while (1) {
printf("choose an option [1-3]: ");
scanf("%d", &option);
if (option != 1 || option != 2 || option != 3) {
printf("\nInvalid option.\n");
} else if (option == 1) {
/* do something */
} else if (option == 2) {
/* do something */
} else if (option == 3) {
/* do something */
}
}