【发布时间】:2019-09-18 05:15:39
【问题描述】:
头文件:
#include <stdio.h>
#include <stdlib.h>
int print_menu(){
printf ("MENU\n");
printf ("1. Total of All Top Scores for the Week\n");
printf ("2. Total of All High Scores for the Week\n");
printf ("3. Total Machine High Scores for the Week\n");
printf ("4. Machine High Score for the Week\n");
printf ("5. EXIT\n");
printf ("Enter Selection:");
int selection = getchar();
return selection;
}
主 C 文件:
#include <stdio.h>
#include <stdlib.h>
#include "lab1.h"
int main(int argc, char *argv[]){
int selection = print_menu();
while(1)
{
switch (selection)
{
case '1':
printf ("\nselected 1\n");
break;
case '2':
printf ("\nselected 2\n");
break;
case '3':
printf ("\nselected 3\n");
break;
case '4':
printf ("\nselected 4\n");
break;
case '5':
printf ("\nExit\n");
exit(0);
break;
default:
printf ("Invalid Selection");
print_menu();
break;
};
};
}
我的问题是,当我运行程序并输入错误的字符时,程序应该重新打印菜单并再次要求选择。除了它两次打印菜单。示例:
maiah@maiah-vb:~/shared$ ./a.out
MENU
1. Total of All Top Scores for the Week
2. Total of All High Scores for the Week
3. Total Machine High Scores for the Week
4. Machine High Score for the Week
5. EXIT
Enter Selection:d
Invalid Selection
MENU
1. Total of All Top Scores for the Week
2. Total of All High Scores for the Week
3. Total Machine High Scores for the Week
4. Machine High Score for the Week
5. EXIT
Enter Selection:
Invalid Selection
MENU
1. Total of All Top Scores for the Week
2. Total of All High Scores for the Week
3. Total Machine High Scores for the Week
4. Machine High Score for the Week
5. EXIT
Enter Selection:
然后您可以选择输入另一个选项。 当我通过时,我注意到它似乎正在选择“d”并正确输出,但随后自动输入空格或新行并继续检查选择(我不确定这是否是但实际问题 - 这就是它的表现方式)。如果有人对如何解决此问题有任何想法并解释为什么会发生这种情况。任何帮助都会很棒!
【问题讨论】:
-
不要将代码放在标题中。
标签: c loops while-loop menu switch-statement