3

I can't do this in C++

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

why????

1
  • 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. Commented Nov 16, 2012 at 17:09

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

Comments

6
atoi(temp.c_str()) 

Comments

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.

Comments

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.

Comments

0

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

Comments

-1
int i = 12345; std::string s; std::stringstream sstream; sstream << i; sstream >> s; 

1 Comment

This is int to string. He want string to int.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.