gpt4 book ai didi

c - 处理错误输入后如何重复菜单

转载 作者:行者123 更新时间:2023-11-30 15:03:00 27 4
gpt4 key购买 nike

所以分配是打印一个带有选项的菜单,如果用户输入了无效的选择(不是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) {
.

}

*while(1)是针对整个代码的,放置整个代码以供重用

** 我没有使用 switch-case,因为它被禁止使用

现在的问题是,如果我首先输入了错误的输入,例如“7”(这不是菜单中的选项),它将打印“错误输入,请重试”。到目前为止,一切都很好。但是,如果我按 2 重新打印菜单,然后按任何数字,即使它是有效的选择,它也会打印“错误输入”。另外,如果我按“2”重新打印菜单,然后按 1,则需要按 1 两次才能退出程序,而不是只按一次。

最佳答案

上面的答案看起来是正确的,但您可以使用以下代码,因为它的工作原理对任何人来说都很容易理解!

    #include <stdio.h>
void printMenu()
{
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. ");
}
int main()
{

int choiceValid=0, count=0, choice;

printMenu();
while(choiceValid==0 && count<=5)
{
printf("Enter your choice: ");
scanf("%d" , &choice);

if(choice==2)
{
printMenu();
continue;
}
if( choice<=6 && choice>=1 )
choiceValid=1;
else
{
count++;
printf("\nWrong input, please try again (Enter 2 for re-printing the menu). \n " );
}
}
return 0;
}

关于c - 处理错误输入后如何重复菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40896043/

27 4 0