cnumbersatoi

C - Check if given argument is natural number


How should I correctly check if given argument is a natural number in C? I am a very beginner when it comes to C... I already have compared that argument to 1 and 2 by atoi(argv[1]) == 1 ..., but when I pass let's say 1.2137 as an argument, atoi cuts it to 1. Thanks for any help.


Solution

  • You can either use long strtol(const char* nptr, char** endptr, int base) from the header stdlib.h to check if your whole string can be converted to a number:

    char* end;
    strtol( argv[1], &end, 10 );
    if( *end == '\0' ){
        printf( "String is a natural number\n" );
    } else {
        printf( "String is not a natural number\n" );
    }
    

    Another way would be to check for characters that are not '+', '-' or digits

    bool valid = true;
    for( const char* it = argv[1]; *it; ++it ){
        if(!(( *it >= '0' && *it <= '9' ) || *it == '+' || *it == '-' )){
            valid = false;
        }
    }
    printf( "String is%s a natural number\n", valid ? "" : " not" );