为什么digit()不起作用?

时间:2015-01-23 15:18:03

标签: c debugging scanf

我正在尝试创建一个生成随机数的程序,要求用户猜测,然后回答他是否正确。出于某种原因,无论用户是否输入数字,它都会响应,就好像他没有。有任何想法吗?感谢帮助初学者:)

#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);
}

1 个答案:

答案 0 :(得分:5)

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