2

I can't do this in C++

string temp = "123";
int t = atoi(temp);

why????

rahul
  • 184,426
  • 49
  • 232
  • 263
Alex
  • 31
  • 2
  • A lot of the answers have said you can't do it because the function takes a const char* so call .c_str(). Fair enough, and correct. But I would ask the question why haven't all the functions that take a const char* been overloaded in c++ to take a const std::string& too, it seems like that would have been an obvious thing to do. – jcoder Nov 16 '12 at 17:09

6 Answers6

8

That is because atoi is expecting a raw const char* pointer. Since there is no implicit conversion from std::string to const char* you get a compiler error. Use c_str() method of std::string to get a c-style const char* for a std::string object. BTW, in C++ you can use streams to do this conversion instead of using these C-style APIs.

Naveen
  • 74,600
  • 47
  • 176
  • 233
6
atoi(temp.c_str())
Jonathan Graehl
  • 9,182
  • 36
  • 40
3

See these questions:

C atoi() string to int: Points out that atoi() is deprecated.

Why doesn't C++ reimplement C standard functions with C++ elements style?: Gives alternate ways to do what you've listed above.

Community
  • 1
  • 1
Chip Uni
  • 7,454
  • 1
  • 22
  • 29
1

Well, you passed a std::string (presumably) to atoi, which takes a const char*. Try:

atoi(temp.c_str());

which was previously mentioned. Instead, you could use boost's lexical_cast:

std::string temp = "123";
try {
   int foo = boost::lexical_cast<int>(temp);
} catch (boost::bad_lexical_cast e) {
   //handle error here
}

You could wrap the try/catch into a template function that handles the exceptions in the event that you do not already have exception handling in place.

s1n
  • 1,434
  • 11
  • 10
0

std::string is not the same as a character pointer (like in C).

swlkr
  • 210
  • 5
  • 11
-1
int i = 12345;

std::string s;

std::stringstream sstream;

sstream << i;

sstream >> s;
Coding Mash
  • 3,338
  • 5
  • 24
  • 45
mindhacks
  • 509
  • 1
  • 4
  • 6