سؤال

Possible Duplicate:
Converting string to integer C

I wanted to convert a number I received from the command argv[1] into an "int". I know the argv is stored as a string, but how can I get an integer value from them. Supposing argv[1] = 10.

هل كانت مفيدة؟

المحلول

You can use the atoi() function from the C standard library:

http://en.cppreference.com/w/cpp/string/byte/atoi

نصائح أخرى

The POSIX C library includes different functions to convert strings to actual numerical values. Here are a few examples:

long some_long = strtol(argv[1], NULL, 10);
long long some_longlong = strtoll(argv[1], NULL, 10);
unsigned long some_unsigned_long = strtoul(argv[1], NULL, 10);
unsigned long long some_unsigned_longlong = strtoull(argv[1], NULL, 10);

There are functions even for conversion to floating-point values:

double some_double = strtod(argv[1], NULL);
float some_float = strtof(argv[1], NULL);
long double some_long_double = strtold(argv[1], NULL);

For further reference, read here and some more places (strtoul.html and strtod.html on the same web page).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top