2014-11-15 38 views
0

好吧它現在循環正確,但是當你給它一個輸入例如'2'它只是默認情況下。C程序,開關菜單無限循環

print_Menu() { 
     while (1) 
    { 
     printf("=============================================\n"); 
     printf("MENU\n"); 
     printf("=============================================\n"); 
     printf("1. Do stuff\n2. Do more stuff\n3. Do even more stuff\n4. Quit\n"); 
     printf("Choose an option: "); 

     scanf(" %s*", &selection); 


     switch (selection) { 
      case 1: 
       /*do your thing for option 1*/ 
       printf("thing 1\n"); 
       break; 
      case 2: 
       /*do your thing for option 2*/ 
       printf("thing 2\n"); 
       break; 
      case 3: 
       /*do your thing for option 3*/ 
       printf("thing 3\n"); 
       break; 
      case 4: 
       /*do your thing for option 3*/ 
       printf("quiting app\n"); 
       exit(0); 
       break; 
      default: 
       printf(" Invalid selection\n"); 
       // print_Menu(); 
       break; 
     } 
     } 
+1

通過不正確的輸入,你的意思是不在1-4範圍內的整數,或者你的意思是不是一個整數? –

+2

你真的想要在默認情況下遞歸調用函數嗎? – Leeor

回答

3

default情況下,只需添加

scanf("%*s"); 

以清除輸入buffer.The *告訴scanf掃描一個字符串,然後將其丟棄無效字符(S)。

scanf無法獲得整數,並且在輸入除整數以外的任何其他東西時返回0。這些數據不會被scanf消耗,因此仍保留在stdin中。當第二次調用scanf時,它會看到先前輸入的字符,然後再次無法讀取整數。這將導致無限循環

+0

非常感謝! :) – Sparky3295

+0

@ Sparky3295不要調用'printMenu()'遞歸。 –

+1

@ Sparky3295,同時指定函數定義之前的返回類型(我認爲你需要'void') –

0
if(1!=scanf("%d", &selection)){ 
    while(getchar() != '\n'); 
    selection = -1; 
}