What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).
What's the C++ way of parsing a string (given as char *) into an int? Robust and clear error handling is a plus (instead of returning zero).
This is a safer C way than atoi()
const char* str = "123";
int i;
if(sscanf(str, "%d", &i) == EOF )
{
/* error */
}
C++ with standard library stringstream: (thanks CMS )
int str2int (const string &str) {
stringstream ss(str);
int num;
if((ss >> num).fail())
{
//ERROR
}
return num;
}
With boost library: (thanks jk)
#include <boost/lexical_cast.hpp>
#include <string>
try
{
std::string str = "123";
int number = boost::lexical_cast< int >( str );
}
catch( const boost::bad_lexical_cast & )
{
// Error
}
Edit: Fixed the stringstream version so that it handles errors. (thanks to CMS's and jk's comment on original post)
The good 'old C way still works. I recommend strtol or strtoul. Between the return status and the 'endPtr', you can give good diagnostic output. It also handles multiple bases nicely.
You can use Boost's lexical_cast, which wraps this in a more generic interface.
lexical_cast<Target>(Source) throws bad_lexical_cast on failure.
You can use the a stringstream from the C++ standard libraray:
stringstream ss(str);
int x;
ss >> x;
if(ss) { // <-- error handling
// use x
} else {
// not a number
}
The stream state will be set to fail if a non-digit is encountered when trying to read an integer.
See Stream pitfalls for pitfalls of errorhandling and streams in C++.
You can use stringstream's
int str2int (const string &str) {
stringstream ss(str);
int num;
ss >> num;
return num;
}