-1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Josh
  • 3,231
  • 8
  • 37
  • 58

2 Answers2

2

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

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

Eugene Osovetsky
  • 6,443
  • 2
  • 38
  • 59
  • -1 for adivising the use of a non-standard function where a standard one is available AND answering using a link only. –  Oct 06 '12 at 20:59
  • @H2CO3 You're wrong, `atoi` is standardized - both C and C++ standards include it. Maybe you had `itoa` in mind? –  Oct 07 '12 at 13:18
  • @jons34yp absolutely right! I'm always confusing these. Sorry. –  Oct 07 '12 at 13:32
1

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).