簡體   English   中英

為什么isdigit()不起作用?

[英]Why doesn't isdigit() work?

我正在嘗試制作一個生成隨機數的程序,要求用戶進行猜測,然后響應他是否正確。 由於某種原因,無論用戶是否輸入數字,它都會做出響應,好像他沒有輸入數字一樣。 有任何想法嗎? 感謝您幫助初學者:)

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


main()
{
    char iRandomNum = '\0';

    int iResponse = 0;
    srand(time(NULL));

    iRandomNum = (rand() % 10) + 1;

    printf("Guess the number between 1 yand 10 : ");
    scanf("%d", &iResponse);

    if (isdigit(iResponse) == 0)
        printf("you did not choose a number\n");
    else if (iResponse == iRandomNum)
        printf("you guessed correctly\n");
    else 
        printf("you were wrong the number was %c", iRandomNum);
}

isdigit()采用字符的ascii值,如果不是數字,則返回0如果不是,則返回非0

您正在傳遞給它一個不一定是ascii值的整數值,因為您用scanf()讀取它,所以不需要檢查它是否是數字。

如果要確保scanf()確實讀取了一個數字,請改為檢查scanf()的返回值。

嘗試這個

if (scanf("%d", &iResponse) != 1)
    printf("you did not choose a number\n");

而不是if (isdigit( ...

還有一件事, main()必須返回int

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM