sdigit函数在c中我的代码有什么问题?

时间:2016-02-20 18:51:55

标签: c

我的代码出了什么问题?即使我输入一个数字在1-10之间或其他任何东西,它直接进入"你没有输入正确的号码"

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

 int main()
 {
  // CREATE A VARIABLE TO  STORE A RANDO NUMBER ITS TIME THE PROGRAM   RUNS

  int numdef, randomnum ;

  //ASSIGN RANDOM NUMBER
   numdef = (rand() % 11);

   //PROMT USER TO  GUESS A NUMBER BETWEEN 1-10
   printf("Please enter a number between 1-10\n");
   scanf("%d", &randomnum);


   // USE  SDIGIT  TO  VERIFY  THAT USER ENTERS A DIGIT

    if (isdigit(randomnum))


          printf("correct");

    // LET  HIM  KNOW IF HE IS CORRECT  OR NOT

     else

printf("\nYou did  not enter a correct  number FOOL!!!,please  try again! \n");


return 0;

}

1 个答案:

答案 0 :(得分:4)

因为isdigit()检查传递的值是否是数字的ascii代码。您正在向其传递一个数字,因此它始终提供0

isdigit()检查x的值是否满足'0' < x < '9',其中'0''9'是字符0的ascii值和9分别为4857

您正在使用scanf()阅读一个数字,您无需检查是否为数字。必须提供scanf()成功,以验证您必须检查scanf()的返回值,它是成功扫描的占位符的数量。

所以在你的情况下

if (scanf("%d", &randomnum) != 1) // The 1 is for the lonely "%d"
    printf("Error, the text entered is not a number\n");
else
    printf("You entered `%d'\n", randomnum);

// Trying to read from `randomnum' here is dangerous unless it was
// initialized before `scanf()'.