因此,分配方式是打印带有选项的菜单,如果用户输入无效选项(不是1,2,3,4,5,6),则打印出错并要求用户再次选择。 如果用户总共输入5次错误的输入,程序将退出。如何处理错误的输入后重复菜单
int main() {
printf("Welcome, please choose one of the options below: \n ");
printf("1.Exit \n ");
printf("2.Print menu again \n ");
printf("3. ");
printf("4.. ");
printf("5. ");
printf("6. ");
printf("Enter your choice: ");
scanf("%d" , &choice);
if((choice > 6) || (choice < 1)) {
do {
count++;
printf(" Wrong input, please try again (Enter 2 for re-printing the menu). \n ");
printf("Enter your choice: ");
scanf("%d", &choice);
if(choice==2){
do {
printf("Welcome, please choose one of the options below: \n "); //prints of the screen the following in a loop
printf("1.Exit \n ");
printf("2.Print menu again \n ");
printf("3. ");
printf("4. ");
printf("5. ");
printf("6.");
printf("Enter your choice: ");
scanf("%d", &choice);
} while (choice==2);
}
} while (count < 4) ;
printf("%s" , "You have made 5 menu errors.Bye Bye!!! \n ");
}
while(1) {
.
}
*的同时(1)被用于整个代码,把整个代码以供再使用
**我没有使用的switch-case辩论,因为它禁止使用
现在,问题是,如果我先输入错误的输入,比如'7'(这不是菜单中的选项),它会打印“错误的输入,请重试”。到现在为止还挺好。 但是,如果我按2重新打印菜单,然后按任意数字,即使这是一个有效的选择,它也会打印“错误的输入”。 另外,如果按'2'重新打印菜单,然后按1,则需要按两次才能退出程序,而不是只按一次。
将菜单放在它自己的函数中,所以你可以在需要显示菜单的任何位置调用该函数。 – user3386109
你提到哪个菜单?因为我打印了两次。一次在int main之下,并且一旦进入循环 – Invader
,我会添加一个名为'usage()'或类似的子程序或方法,并且每次调用该函数而不是打印出实际的菜单。我不是一个c程序员,但我在bash/shell脚本中这样做。 – Stuart