spliting a *char to int

Hello everyone,

Im having some trouble with a bit of code im trying to write,
im using command line arguments to get input from the user as options for the program im doing. But as one of the options they have to enter -r followed by a number without any spaces in between, eg. -r1001.

Since it is stored as a char from main(int argc, char* argv) is there a way to split -r1001 and just store the number, 1001 only into an int without the -r?

iv tried using atoi(), eg.

int i;
i = atoi(argv[1]); // argv[1] is -r1001
printf("This is: %d \n", i);

but it returns a 0 everytime.

Any ideas how i can store only the number as an int???


Thanks
Try i = atoi( argv[i] + 2 ); to skip the first two characters.
You can brute force it with atoi(&(argv[1][2])) (address of the second byte of the first option).

Or you could use the Unix getopt() functions to parse the command line. It's useful for complicated command-line parsing. But it takes a little more coding to make it work. The Linux manpage for getopt(3) has an example where they parse a number after an option exactly as you need.
atoi(&(argv[1][2])) is simply a wordier version of atoi(argv[i]+2).
Topic archived. No new replies allowed.