2015-03-08 39 views
0

我一直在編寫一個程序,它接受輸入並檢查數字是偶數還是奇數,並在輸入是字符而不是數字時輸出錯誤消息我的初始代碼爲:在while循環中用scanf()檢查輸入類型

int main() 
{ 
    int x; 
    int check = scanf("%d", &x); 
    printf("input: "); 
    while(check != 1){ //means that the input is inappropriate 
     printf("Error!: unexpected input\n"); 
     printf("input: "); 
     check = scanf("%d", &x); 
    } 
    if(x%2 == 0){ 
    printf("It's even\n"); 
    }else{ 
    printf("It's odd\n"); 
    } 
return 0; 
} 
當我運行一個無限循環的印刷

「錯誤!:意外輸入\ n」個 但是當我把下面的語句在while循環中它工作正常的說法是:scanf("%s",&x); 有人可以解釋這個行爲?

回答

0

int check = scanf("%d", &x);不消耗「輸入是字符而不是數字」,將該輸入保留爲stdin以用於下一個輸入函數。由於下一個輸入函數是check = scanf("%d", &x);,因此它不會消耗違規數據,因此循環重複。

代碼需要讀取「輸入一個字符不是數字」比scanf("%d", ...)


其他東西,而不是一個小的修復混亂,建議使用從未scanf()。讀取輸入與fgets()getline(),然後用ssscanf()strtol()解析等

int main(void)  { 
    int x; 
    char buf[100]; 
    while (printf("input: "), fgets(buf, sizeof buf, stdin) != NULL) { 
     int check = sscanf(buf, "%d", &x); 
     if (check == 1) break; 
     printf("Error!: unexpected input\n"); 
    } 
    if(x%2 == 0){ 
     printf("It's even\n"); 
    }else{ 
     printf("It's odd\n"); 
    } 
    return 0; 
}