A simple and typesafe solution using only C++ facilities is the following approach:
#include <iostream>
#include <sstream>
int fromString(const std::string& s)
{
std::stringstream stream;
stream << s;
int value = 0;
stream >> value;
if(stream.fail()) // if the conversion fails, the failbit will be set
{ // this is a recoverable error, because the stream
// is not in an unusable state at this point
// handle faulty conversion somehow
// - print a message
// - throw an exception
// - etc ...
}
return value;
}
int main (int argc, char ** argv)
{
std::cout << fromString ("123") << std::endl; // C++03 (and earlier I think)
std::cout << std::stoi("123") << std::endl; // C++ 11
return 0;
}
Note: that in fromString()
you should probably check to see if all characters of the string actually form a valid integral value. For instance, GH1234
or something wouldn't be and value would remain 0 after invoking operator>>
.
EDIT: Just remembered, an easy way to check if the conversion was successful is to check the failbit
of the stream. I updated the answer accordingly.