How to cast program argument *char as int correctly

ccastingcharpointers

I'm on a Mac OS X 10.6.5 using XCode 3.2.1 64-bit to build a C command line tool with a build configuration of 10.6 | Debug | x86_64. I want to pass a positive even integer as an argument, so I'm casting index 1 of argv as an int. This seems to work, except it seems that my program is getting the ascii value instead of reading the whole char array and converting to an int value. When I enter 'progname 10', it tells me that I've entered 49, which is what I also get when I enter 'progname 1'. How can I get C to read the entire char array as an int value? Google only showed me (int)*charPointer, but clearly that doesn't work.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(int argc, char **argv) {
    char *programName = getProgramName(argv[0]); // gets the name of itself as the executable
    if (argc < 2) {
        showUsage(programName);
        return 0;
    }
    int theNumber = (int)*argv[1];
    printf("Entered [%d]", theNumber);            // entering 10 or 1 outputs [49], entering 9 outputs [57]
    if (theNumber % 2 != 0 || theNumber < 1) {
        showUsage(programName);
        return 0;
    }

    ...

}

Best Answer

The numer in the argv array is in a string representation. You need to convert it to an integer.

sscanf

int num;
sscanf (argv[1],"%d",&num);

or atoi() (if available)