检查输入的值是否为整数

时间:2014-04-13 19:32:17

标签: c typechecking

所以有我的代码

void otherdata(int* targetValue, int* count){
    char buffer[256];
    while (1) {
        if (fgets(buffer, sizeof(buffer), stdin)) {
            int lsize = atoi(buffer);
            if (isdigit(lsize) != 0) {
                printf("Target value: %d entered\n", lsize);
                *targetValue = lsize;
                return;
            } else {
            printf("Invalid input. Try again.\n");
            }
        }
    }
}

对我而言似乎应该有效,但事实并非如此。我认为问题在于isdigit(),但我不知道如何检查它是否为num。

1 个答案:

答案 0 :(得分:0)

void otherdata(int* targetValue, int* count){
    char buffer[256];
    while(1) {
    if (fgets(buffer, sizeof(buffer), stdin)) {
        int lsize = atoi(buffer);
        if (isdigit(*buffer) != 0) {             // <<< Changed this line.
            printf("Target value: %d entered\n", lsize);
            *targetValue = lsize;
            return;
        } else {
        printf("Invalid input. Try again.\n");
        }
    }
}

}