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
#include
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)