views:

189

answers:

6
+2  Q: 

string to integer

I can't do this in C++

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

why????

+6  A: 
atoi(temp.c_str())
wrang-wrang
+8  A: 

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
A: 

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

swlkr
+3  A: 

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.

Chip Uni
+1  A: 

int i = 12345;

std::string s;

std::stringstream sstream;

sstream << i;

sstream >> s;

mindhacks
+1  A: 

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