4
votes

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;
    }

    ...

}
4

4 Answers

19
votes

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)

9
votes

Casting can't do that, you need to actually parse the textual representation and convert into integer.

The classical function for this is called atoi(), but there's also strtol() or even sscanf().

1
votes

Lets say you have a 9 as argument. You said you are getting 57, the ascii value.

Use the fact that int num = *arg[1] - '0' will give you back the number you need.

if it's a larger number like, 572 then you need

char *p = argv[1];
int nr = 0;
int i;
for(i =0; i< strlen(p); i++) {
    nr = 10 * nr + p[i] - '0';
}

Add some error checking and its good to go.

Or, depending on what you have, you can use some functions like atoi(), sscanf() etc.

0
votes

Use atoi() or strol() functions.