开发者

How to convert a string pointer to a 64bit ( _int64) variable?

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 开发者_如何学Goproblems....


You can use _atoi64, _strtoi64 functions in stdlib.h


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


#include <stdlib.h>

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


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 */


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜