2015-09-22 67 views
0

我想在爲了使用以後計算使用scanf()一個int閱讀,但我試圖把它丟棄INT後什麼。,而忽略其他任何

基本上我希望能夠提示用戶回答,因爲

什麼是3 + 5這樣的問題?

,併爲用戶能夠輸入8個或8狗或性質的任何東西,同等對待。我嘗試過使用scanf("%*[^\n]\n");,但是這會導致其他提示 無法正確顯示,導致程序中的其他問題。我還應該知道,在其他計算中需要讀取的值(在這種情況下爲8),並且我需要刪除狗部分,因爲它會在程序中稍後導致問題。

示例代碼,以澄清意見

printf("What is %d %c %d ", a, oper, b); 
fgets(line, sizeof(line), stdin); 
errno = 0; 
num = strtol(line, NULL, 10); 
if (num == answer) 
    { 
    printf("Correct!"); 
    right++; 
    } 
else 
    { 
    printf("Wrong!"); 
    } 
printf("\n"); 

    if (errno != 0) 
{ 
    printf("Invalid input, it must be just a number \n"); 
} 

基本上這部分牌號用戶輸入

+1

這應該這樣做。 – Olaf

+1

爲什麼在使用'fgets()'時使用'scanf()'好得多? – chux

+0

使用它只有一次的問題是,在int之後的狗或任何垃圾仍然保留在標準輸入中,並擰緊下一個提示信息 – tacoofdoomk

回答

2

使用scanf可能會非常棘手試圖以這種方式來讀取輸入時,一個數學問題的問題。我建議使用fgets整行讀取,然後使用strtol將結果轉換爲數字。

char line[100]; 
long int num; 
fgets(line,sizeof(line),stdin); 
errno = 0; 
num = strtol(line, NULL, 10); 
if (errno != 0) { 
    printf("%s is not a number!\n", line); 
} 

編輯:

你有什麼看起來不錯,但作爲chux在評論中指出,這是不正確檢測非數值。如果你想忽略任何如下,只是'的scanf( 「%d」,&my_int)`正好一次

int main() 
{ 
    int a, b, answer, right;; 
    char oper, *p; 
    char line[100]; 
    long int num; 

    right=0; 
    a=3, b=5, oper='+', answer=8; 
    printf("What is %d %c %d ", a, oper, b); 
    fgets(line, sizeof(line), stdin); 
    errno = 0; 
    num = strtol(line, &p, 10); // p will point to the first invalid character 
    if (num == answer) 
    { 
     printf("Correct!"); 
     right++; 
    } 
    else 
    { 
     printf("Wrong!"); 
    } 
    printf("\n"); 

    if (errno != 0 || p == line) 
    { 
     printf("Invalid input, it must be just a number \n"); 
    } 
} 
+3

迂腐音讀字符輸入值:有4次測試,可以按照'與strtol(行中的&endptr,10)'讀取一個'int':'if(errno)'檢測溢出,'如果num chux

+0

這似乎不起作用,當我嘗試使用變量時,我得到的後來它不能以我獲得的變量的方式工作scanf函數。我需要能夠使用num值進行其他計算 – tacoofdoomk

+0

@tacoofdoomk你能發表一些示例代碼來說明問題嗎? – dbush