#include <boost/lexical_cast.hpp> #include <string> int main() { std::string str = "12345"; int i; try { i = boost::lexical_cast<int>(str); } catch( const boost::bad_lexical_cast & ) { //unable to convert } return 0; }
Treat command line arguments as a sequence of numeric data
Source: http://www.boost.org/libs/conversion/lexical_cast.htm
#include <boost/lexical_cast.hpp> int main(int argc, char * argv[]) { using boost::lexical_cast; using boost::bad_lexical_cast; std::vector<int> args; while(*++argv) { try { args.push_back(lexical_cast<int>(*argv)); } catch(bad_lexical_cast &) { args.push_back(0); } } return 0; }
boost::lexical_cast is type safe and throws an exception on error, eliminating the need for manual error checking.
