I can't do this in C++
string temp = "123";
int t = atoi(temp);
why????
I can't do this in C++
string temp = "123";
int t = atoi(temp);
why????
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.
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.
int i = 12345;
std::string s;
std::stringstream sstream;
sstream << i;
sstream >> s;
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.