简体   繁体   中英

Why doesn't isdigit() work?

I'm trying to make a program that generates a random number, asks the user to guess and then responds whether or not he got it right. For some reason, regardless of wether the user puts in a digit or not, it responds as if he didn't. Any ideas? thanks for helping out a beginner :)

#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() takes the ascii value of a character and returns 0 if it's not a digit and non- 0 if it is.

You are passing to it an integer value which is not necessarily an ascii value, you don't need to check if it's a digit since you read it with scanf() .

If you want to make sure scanf() did read a number, check the return value of scanf() instead.

Try this

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

instead of the if (isdigit( ...

One more thing, main() must return int .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM