2016-11-30 105 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