2014-09-18 72 views
-1

這是我的程序。檢查C中是否有正確的輸入

reprocess: 

    printf("Enter number: 1,2,3 "); 

    if(scanf("%d%c", &preproc, &term)!= 2 || term!= '\n'){ 
     printf("Invalid Input"); 
     goto reprocess; 


    }else{ 

     if ((preproc==1) || (preproc==2) || (preproc==3)){ 
     printf("Correct Input\n"); 

     }else{ 
     printf("Invalid Input %d \n", preproc); 
     goto reprocess; 

     } 
    } 

爲什麼如果我輸入一個字符串,它不會停止循環?請指導我。

+0

你明確地寫道,如果他們輸入一個字符串,然後'轉到重新處理;'。你期望什麼? – 2014-09-18 23:33:14

+0

@AdamSinclair吧?此代碼僅打印「無效輸入」(可能後跟一個數字)或「正確輸入」。 – 2014-09-18 23:37:12

+0

這只是某種輸入檢查器。 – user3339866 2014-09-18 23:39:33

回答

1

試試這個

if(scanf("%d%c", &preproc, &term)!= 2 || term!= '\n'){ 
    printf("Invalid Input\n"); 
    scanf("%[^\n]");//this will skip the input when there is a non-numeric input. 
    goto reprocess; 
}else{