converting c++ String to int

Started by
2 comments, last by MaulingMonkey 19 years ago
how do i convert a string to a int? in c++ useing the <string> class [Edited by - Solance on April 11, 2005 8:32:45 PM]
Advertisement
Try using atoi() or atof()
eg..

String msg = "52";
cout << atoi(msg.c_str());

outputs 52
yes i was using that function before i made this post, it seemed to work but then i changed the varaiable and it seems to be saying every number is 0
The methods:

1) From the C standard library, using atoi:

#include <cstdlib>#include <string>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 <sstream>#include <string>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 <boost/lexical_cast.hpp>#include <string>try{    std::string text = "152";    int number = boost::lexical_cast< int >( text );}catch( const boost::bad_lexical_cast & ){    //unable to convert}


Out of the three I prefer the last one, as it makes the most sense to myself, and I like exceptions :). See http://boost.org/index.htm for information about the boost library. One can of course use "using namespace std;" and "using namespace boost;" to remove the std:: and boost:: prefixes in all the examples.

This topic is closed to new replies.

Advertisement