2017-09-15 23 views
-2

新手C學生在這裏。isdigit()對於整數10及以上返回true

有人能解釋爲什麼isdigit()返回值爲10+的值爲true嗎? 我正在做一個關於猜謎遊戲的非常基本的任務,並且必須使用isdigit()來通知用戶他是否輸入了數字1-10。 該程序似乎運行良好,否則,我只想知道isdigit()返回值爲10 +的值爲true的原因。

#include <stdio.h> 
#include <stdlib.h> 
#include <ctype.h> 
#include <time.h> 

int main() 
{ 
int iRandomNum = 0; 
char cResponse = '0'; 

srand(time(NULL)); 
iRandomNum = (rand() % 10) + 1; 

printf("\nGuess a number between 1 and 10: "); 
scanf("%c", &cResponse); 

if (!isdigit(cResponse) || cResponse<'0'+1) 
    printf("\nYou did not enter a number 1-10"); 

else if ((cResponse - '0') == iRandomNum) 
    printf("\nCorrect!"); 

else 
{ 
    printf("\nSorry, you guessed wrong\n"); 
    printf("The correct guess was %d\n", iRandomNum); 
} 
return 0; 
} 
+3

只評估第一個字母(數字)(輸入)。 – BLUEPIXY

+1

'10'不是一個數字! 'cResponse <'0'+1' ->'cResponse <'1''。但是,這並不意味着你要麼。 – Olaf

回答

0

你傳遞一個charisdigit,只能容納一個字符。因此,雖然您可能正在輸入10,但只有第一個字符(它是一個數字)進入cResponse

+0

這樣做很有意義 - 謝謝! – ybur

+0

我在想,如果我輸入一個雙字符的值,它會返回false。這是非常有用的知道在這種情況下isdigit不考慮任何超出第一個字符。 – ybur

+0

它不是'isdigit'。正如你從我的答案中的日誌中可以看到的那樣,'cResponse'本身只包含一個字符,因爲你要求'scanf'只讀取一個字符。 –

0

而不是閱讀用戶輸入作爲字符,讀取它作爲int。這樣你就可以使用if(guess >= 1 && guess <= 10)。由於你需要10作爲輸入範圍的一部分,char(它是一個單獨的字符)不會這樣做。你要麼需要使用一個字符串(這會使事情更復雜),或者只是使用一個int。

4

如果添加printf登錄的cResponse的價值,問題就會變得很快顯示出來:

printf("\nGuess a number between 1 and 10: "); 
scanf("%c", &cResponse); 

printf("cResponse is %c\n", cResponse); 

輸出:

Guess a number between 1 and 10: 10 
cResponse is 1 

正如你所看到的,只有第一個字符是存儲在cResponse(這是有道理的,因爲它只是一個字符),並且由於第一個字符是一個數字,您的isdigit()調用返回true。

如果你想讀的數字大於10,你可以閱讀到int代替:

int cResponse = 0; 

printf("\nGuess a number between 1 and 10: "); 
scanf("%d", &cResponse); 

printf("cResponse is %d\n", cResponse); // prints '10' if I type '10' 

請注意,您不能在這種情況下使用isdigit(),但你仍然可以使用if (cResponse >= 0 && cResponse <= 10)輕鬆地檢查你的邊界。

+0

這真棒,謝謝! – ybur

相關問題