Sign in to follow this  

converting c++ String to int

This topic is 4663 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
Sign in to follow this