views:

121

answers:

5

As I wrote an app with the function main(int argc, char * argv[])

When i start up the application, I wanna send some parameters like (assume the app name is ffdisk)

>ffdisk -f 111123123131321312312123 1

You see the third param maybe an int64 param in my original intention...
But in function main, argv[2] is string pointer, so how can convert this string into a int64 variable?

Thanx...
I am always stuck at messy problems....

+2  A: 

There're multiple ways, use some argc/argv parsing library, or manually use sscanf or atol library functions.

Drakosha
+2  A: 

You can use _atoi64, _strtoi64 functions in stdlib.h

Prashant
I took your suggestion with _atoi64...thanx
Macroideal
A: 

For Linux, the GNU C library has getopt. For Windows you can have a look at XGetopt

Or you can have a look at argtable (but I never had the opportunity to use it)

Also in C++:

Boost.Program_options allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.

or

The gflags package contains a library that implements commandline flags processing. As such it's a replacement for getopt(). It has increased flexibility, including built-in support for C++ types like string, and the ability to define flags in the source file in which they're used.

Just pick one.

Gregory Pakosz
+2  A: 
#include <stdlib.h>

int main(int argc, char** argv) {
     second_parm_as_long_long = atoll(argv[2]);
     return 0;
}
drhirsch
+1  A: 

As you're targetting Windows and Linux, you may want to stay well within the functionality present on both systems. That means plain Standard C89.

But plain Standard C89 does not require implementations to provide a 64-bit integer type. So, you're stuck anyway.

Assuming you have a type (implementation dependent) large enough for your needs, you can create the number bit digit by digit ...

value = 0; /* value is of the large enough type */
char *p = argv[2];
while (*p) {
    value *= 10;
    value += *p - '0';
    p++;
}
/* if argv[2] was "111123123131321312312123"
 * and the type is large enough,
 * value now has 111123123131321312312123 */
pmg
seems work well. i'll try it later. thanx
Macroideal