-3

Possible Duplicate:
Convert char array to single int?

I have

char[] str = "124"

I want to get a single int i with i==124. Which function do I have to use?

Community
  • 1
  • 1
Christian
  • 25,249
  • 40
  • 134
  • 225
  • You need to specify more. What do you want for "1E20"? "1E3000000"? "124Hello"? "Hello"? ""? "2,3"? "2.3"? "00000124"? – Daniel Daranas Dec 12 '11 at 11:48
  • 1
    In C++ you say `char str[] = "124"`. – bames53 Dec 12 '11 at 11:51
  • 1
    ¤ Learning to find things in the documentation is one of the most important skills to develop for a beginner. So concentrate on that. Read the documentation, get familiar with it, try to find things before asking here. Or as we said in the old days, with less sensitive learners (or perhaps the point was to weed out the sensitive soft-minded ones), RTFM. Cheers & hth., – Cheers and hth. - Alf Dec 12 '11 at 11:51

4 Answers4

6

std::istringstream, or boost::lexical_cast, if you have Boost.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
1

Try atoi() from the C standard library:

#include <cstdlib>

char str[] = "124";
int i = atoi(str);

Or, possibly better, use strtol():

#include <cstdlib>

char str[] = "124";
int i = strtol(str, NULL, 0);
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • 4
    Don't use `atoi`. There's no error handling. (But `strtol` is a good alternative, which I failed to mention.) – James Kanze Dec 12 '11 at 11:48
  • @James: thanks - I've updated the answer with `strtol()` as a possibly better alternative to `atoi()`. – Paul R Dec 12 '11 at 11:54
0

Use atoi function.

Alse see;

Atoi

Strtol

Strtod

Strtoul

Yusuf K.
  • 4,195
  • 1
  • 33
  • 69
0

Create a stringstream from the char-Array and use << for conversion to int.

Sebastian
  • 8,046
  • 2
  • 34
  • 58