2016-11-30 64 views
0

因此,分配方式是打印带有选项的菜单,如果用户输入无效选项(不是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,则需要按两次才能退出程序,而不是只按一次。

+0

将菜单放在它自己的函数中,所以你可以在需要显示菜单的任何位置调用该函数。 – user3386109

+0

你提到哪个菜单?因为我打印了两次。一次在int main之下,并且一旦进入循环 – Invader

+0

,我会添加一个名为'usage()'或类似的子程序或方法,并且每次调用该函数而不是打印出实际的菜单。我不是一个c程序员,但我在bash/shell脚本中这样做。 – Stuart

回答

0

替换您if(choice==2)if((choice==2) || (choice > 6) || (choice < 1))

替换while (choice==2);用而(((选择== 2)||(选择> 6)||(选择< 1))& &(计数< 4))

将下面的块放在相同的while循环中。

if(2 == choice) count = 0; 
else if (choice > 6) || (choice < 1) count ++; 
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; 
} 
+0

如果您发现答案有用且正确,请给它一个绿色的勾号! – varun