简体   繁体   中英

Using a separate function to check if it's an integer input C Language

#include <stdio.h>
#include <string.h>
#include <math.h>

    void check(char *s){
        char str[24] = s;
        int i;
        fgets(str, sizeof(str), stdin);
        boolean valid = TRUE;
        for (i = 0; i < strlen(str); ++i){
            if (!isdigit(str[i])){
            printf("NOT a valid Integer");
            valid = FALSE;

            break;
            }
        }
        printf("An integer!");
    }

    int main()
    {
        int userInput;
        char str;

        scanf("%d%c", &userInput, &str);
        check(str);
        .
        .
        .


        return 0;
    }

I keep getting error in my code, I'm trying to find a way to use a separate check function to check if the user input a valid integer, ie: numbers like 1,345, 7899,...are good; while typing 'a23','@3','12', '24.4',...will halt the program. Any ideas will help, thanks. C Language.

change your code like this in main function

char str[24];
scanf("%d%s", &userInput, str);

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