简体   繁体   中英

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. 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

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. 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;
}

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