-5

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.

siwakw7
  • 17
  • 1
  • 6

1 Answers1

1

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" );
Orcthanc
  • 49
  • 1
  • 6
  • Note that `strtol()` skips leading whitespace, so if the OP wants to reject strings with leading whitespace they would need to supplement `strtol()` with a test for that. – John Bollinger Dec 06 '20 at 16:46
  • Negative integer numbers don't belong to the _natural numbers_ set, which is made up only by positive integer numbers. – Roberto Caboni Dec 06 '20 at 17:04