ccommand-line

C: Checking command line argument is integer or not?


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.


Solution

  • When you refer argv[1], it refers to a character array containing value 123. isdigit function is defined for a single character input.

    So to handle with this situation, it is better to define a function as follows:

    bool isNumber(const char number[])
    {
        int i = 0;
        
        //checking for negative numbers
        if (number[0] == '-')
            i = 1;
        for (; number[i] != 0; i++)
        {
            //if (number[i] > '9' || number[i] < '0')
            if (!isdigit(number[i]))
                return false;
        }
        return true;
    }