5

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

    ...

}
Rebecca Nelson
  • 1,286
  • 2
  • 9
  • 20

4 Answers4

21

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)

stacker
  • 68,052
  • 28
  • 140
  • 210
9

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().

unwind
  • 391,730
  • 64
  • 469
  • 606
  • 3
    Don't ever use `atoi()`, it might not be available and it does **no** error checking whatsoever: http://stackoverflow.com/questions/2729460/usage-of-atoi-in-the-c-language – Ivo Wetzel Dec 01 '10 at 12:39
  • 1
    @Ivo, atoi is specified by the C standard so likely to be everywhere. It does do error checking, it just reports it in a nonhelpful way (as zero). strtol is a better function, except for quick throwaway code, where it is harder to use. –  Dec 01 '10 at 13:48
1

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.

Milan
  • 15,389
  • 20
  • 57
  • 65
0

Use atoi() or strol() functions.

Šimon Tóth
  • 35,456
  • 20
  • 106
  • 151