Signature of isdigit
int isdigit(int c);
Signature of atoi
int atoi(const char *nptr);
I just wanted to check whether the command line argument passed was an integer or not.Here is the C Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, char *argv[])
{
if (argc == 1)
return -1;
printf ("Hai, you have executed the program : %s\n", argv[0]);
if (isdigit(atoi(argv[1])))
printf ("%s is a number\n", argv[1]);
else
printf ("%s is not a number\n", argv[1]);
return 0;
}
But the output is not as expected, when I am passing a valid number:
$ ./a.out 123
Hai, you have executed the program : ./a.out
123 is not a number
$ ./a.out add
Hai, you have executed the program : ./a.out
add is not a number
I couldn't figure out the error.
isdigit() function checks for a digit character ('0' to '9') which of course depends on ASCII values. Now value returned from your atoi does not fall within ASCII value between '0' to '9'. so it is showing that it is not a number.
When you refer
argv[1]
, it refers to a character array containing value123
.isdigit
function is defined for a single character input.So to handle with this situation, it is better to define a function as follows:
I thought I'd add something to the answers already here. In addition to checking for numbers in base 10, I thought it would be useful to check for and allow hexadecimal numbers as well. I also allow negative numbers.
I also added a few things to check for bad input (e.g. null pointer, letters inside of a string representing a decimal number, or invalid letters inside a string representing a hexadecimal number).
Note that I use the
to_lower(char c)
function to ensure that letters representing hexadecimal will be lower case, just for convenience.I return 1 (or true) if the string is a valid number, 0 if it isn't. If it is a valid number, I store the base inside the parameter base.
I used this function like this:
I don't know what
isdigit
exactly does, but due to name I think it should take achar
argument, check for the char being a digit, is it?I would write like this: (omitted the function shell, just show the core code)
will be:
which will be:
which will be:
since
123
represents the ASCII character'{'
.