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.
Asked
Active
Viewed 6,434 times
-5
-
`atoi` stands for "Ascii to Integer", meaning only whole numbers, if you want floating point numbers, you can use `atof` – Matthew Dec 06 '20 at 15:57
-
1Share some code with us – Abhilekh Gautam Dec 06 '20 at 15:57
-
1Or better yet, [`strtod`](https://en.cppreference.com/w/c/string/byte/strtof) for a function with some validation. – Some programmer dude Dec 06 '20 at 15:57
-
That's right, but I do not want floating point numbers, just want to check if it is not a float – siwakw7 Dec 06 '20 at 15:58
-
2[strtol()](http://www.cplusplus.com/reference/cstdlib/strtol/) si a more advanced function that provides the capability to check the input. – Roberto Caboni Dec 06 '20 at 15:58
-
Alternatively you can traverse `argv[1]` string making sure that all characters are digits (use `isdigit()`). Then you will discard input transalated to 0 by `atoi()` – Roberto Caboni Dec 06 '20 at 16:01
1 Answers
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