I am trying to show the user a menu and allow them to pick from the options. It's in a while loop because it has to iterate until option "e" is picked to exit the program. I included the "default" option as a fail-safe for if the user inputs a value that is not accepted. The default case always runs no matter what I do and the menu always appears twice after the initial run of the code. I have tried changing "getchar()" to the scanf and it still produces the same duplicated output. I have also tried doing away with the switch entirely, but I get the same result using if/then statements. I have attached my full code and any help is appreciated thank you!!
#include <stdio.h>
#include <stdlib.h>
// function for the menu
char menu() {
printf("Please select from the following menu: \n");
// setting up the menu from here
printf("a. input the data files location \n");
printf("b. enter the time interval \n");
printf("c. process and display the US Life Expectancy Data \n");
printf("d. process and display the Statistics of All Data \n");
printf("e. exit the program \n");
}
char options(char choice) {
switch (choice) {
case 'a':
printf("choice a\n");
break;
case 'b':
printf("choice b\n");
break;
case 'c':
printf("choice c\n");
break;
case 'd':
printf("choice d\n");
break;
case 'e':
break;
default: // default when none of the cases are matched
printf("Invalid input\n");
break;
}
}
// main function
int main(void) {
char choice;
do {
menu();
while ((choice = getchar()) == "\n") {};
if (choice == EOF) {
exit(1);
}
options(choice);
} while (choice != 'e');
}
The problem is that your code doesn't handle newlines. In other words when you type a followed by ENTER, your code actually receives two characters. The 'a' and a '\n'. Therefore the menu will be printed twice and you get an "invalid input".
A quick fix could be:
choice = getchar(); --> while ((choice = getchar()) == '\n') {};
That said, you should change choice to be an int and also do:
int choice;
....
....
while ((choice = getchar()) == '\n') {};
if (choice == EOF)
{
// Fatal input error
exit(1);
}
Finally, it's a bad idea to have choice as a global. Instead put it in main and pass it as an argument to the function options. But don't pass it to menu. So do:
char options() { --> char options(int choice) {
and
int main(void) {
int choice;
do {
menu();
while ((choice = getchar()) == '\n') {}; // ignore newlines
if (choice == EOF)
{
// Fatal input error
exit(1);
}
options(choice);
} while (choice != 'e');
}