繁体   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