简体   繁体   English

在不使用函数 isdigit 的情况下使用 fgets 时,如何检查用户输入是否为字符串?

[英]How can I check if a users input is a string when using fgets without using the function isdigit?

I am receiving input that I should be putting into an array, and although I've already implemented methods to check if the array is too short/long, I cannot seem to get around to checking if the array contains non-numeric characters.我收到了应该放入数组的输入,虽然我已经实现了检查数组是否太短/太长的方法,但我似乎无法检查数组是否包含非数字字符。

The array is separated by whitespace and always ends with EOF, and I have that part figured out too.该数组由空格分隔,并始终以 EOF 结尾,我也弄清楚了这一部分。 Here are some methods I've tried but could not solve the issue.以下是我尝试过但无法解决问题的一些方法。 Am I doing something wrong with my code?我的代码有问题吗?

    char *str;
    long nums;
    fgets (line, BUFFER, stdin);
    nums = strtol(line, &str, 10);
    if (str != '\0'){
        printf("Invalid input z");
        return 1;
    }

//but line here only returns the first value before whitespace, which is != to EOF //但是这里的行只返回空格之前的第一个值,即 != 到 EOF

My method of converting the input from fgets into input is by using strtok, before using atoi to convert it to an integer before storing it in the array.我将输入从 fgets 转换为输入的方法是使用 strtok,然后使用 atoi 将其转换为整数,然后再将其存储在数组中。 Is there a better/easier method that works that I'm missing here?有没有更好/更简单的方法,我在这里失踪了? Thanks!谢谢!

EDIT: Here is how I am doing the array编辑:这是我如何做阵列

int count = row * col;
for (int i = 0; i < row && !stop; i++){
    for (int j = 0; j < col && !stop; j++){
        num = strtok(NULL, " ");
        if (num == NULL){ 
            printf("Invalid input 1");
            stop = true;
        }else{
            int curr = atoi(num);
            grid[i][j] = curr;
        }
    }
}

Here's a quick example of what I think you're trying to do.这是我认为您正在尝试做的一个快速示例。


int main() {
    char line[1000];

    char *str;
    long nums;
    fgets (line, 1000, stdin);
    char *next = strtok(line, " \n");
    while (next)
    {
        nums = strtol(next, &str, 10);
        if (*str != '\0') {
            printf("Invalid input %s\n", next);
            return 1;
        }
        printf("Found %ld\n", nums);
        next = strtok(0, " \n");
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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