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;
}
...
}
If it's just a single character 0-9 in ASCII, then subtracting the the value of the ASCII zero character from ASCII value should work fine. If you want to convert larger numbers then the following will do: char *string = "24"; int value; int assigned = sscanf(string, "%d", &value);
All you need to do is: int x = (int)character - 48; Or, since the character '0' has the ASCII code of 48, you can just write: int x = character - '0'; // The (int) cast is not necessary.
argv[1] is a pointer to a string. You can print the string it points to using printf("%s\n", argv[1]); To get an integer from a string you have first to convert it. Use strtol to convert a string to an int .
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)
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()
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With