isDigit()保持返回0,即使它是一个数字,C语言

时间:2014-09-25 06:16:56

标签: c

//Checks if it's an integer, other wise halt the program
    void checkInt(char s[]){
        int i;
        boolean boo = TRUE;
        fgets(s, sizeof(s), stdin);
        for (i = 0; i < strlen(s); ++i){
            printf("%d",isdigit(s[i]));
            if (!(isdigit(s[i]))){
                boo = FALSE;
                printf("Invalid input!\n");
                printf("CLOSING PROGRAM");
                exit(1);
            }
            printf("Cool");
        }  
    }


    int main()
    {
        int userInput;
        scanf("%d", &userInput);
        char buf[sizeof(int)*3+2];
        snprintf(buf, sizeof buf, "%d", userInput);
        checkInt(buf);
        return 0;
    }

我现在已经玩了一段时间了,我似乎不明白为什么我的isDigit总是在我传递数字时返回0?我尝试使用在线Iodeone.com,它按预期工作,但当我使用编译我的老师希望我们使用的,数字突然不知道他们是数字

1 个答案:

答案 0 :(得分:2)

您的代码有些问题:

  1. 您初始化缓冲区以传递给checkInt(),但在checkInt()内,您可以通过调用fgets()来覆盖缓冲区中的内容。

  2. s中的变量checkInt()实际上是一个指针,而不是一个数组,因此sizeof(s)并不能为您提供所需的大小;

  3. 覆盖传递到fgets()的数据的checkInt()可能只是通过stdin调用读取scanf()流中剩下的换行符 - 所以缓冲区基本上设置为等同于"\n"的字符串。这就是isdigit()来电永远不会看到数字的原因。

相关问题