The methods:
1) From the C standard library, using atoi:
#include
#include
std::string text = "152";
int number = std::atoi( text.c_str() );
if (errno == ERANGE) //that may be std::errno
{
//the number was too big/small to store completely, number is either LONG_MAX or LONG_MIN
}
else if (errno == ????)
//maybe EINVAL? not sure, man page dosn't seem to say...
//other possibilities are E2BIG and EDOM (or ERANGE maybe again)...
//but I'd vote for EINVAL
{
//unable to convert to a number
}
2) From the C++ standard library, using strstream:
#include
#include
std::string text = "152";
int number;
std::istringstream ss( text );
ss >> number;
if (! ss.good())
{
//something happened
}
3) From the Boost library, using lexical_cast:
#include
#include
try
{
std::string text = "152";
int number = boost::lexical_castint >( text );
}
catch( const boost::bad_lexical_cast & )
{
//unable to convert
}
文章来源:
http://my.donews.com/robinchow/2007/04/17/post-070417-111701-329/