因此,分配方式是打印帶有選項的菜單,如果用戶輸入無效選項(不是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