Jump to content

  • Log In with Google      Sign In   
  • Create Account

converting c++ String to int


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 Solance   Members   -  Reputation: 100

Like
0Likes
Like

Posted 11 April 2005 - 02:12 PM

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]

Sponsor:

#2 Kristafarii   Members   -  Reputation: 172

Like
0Likes
Like

Posted 11 April 2005 - 02:50 PM

Try using atoi() or atof()
eg..

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

outputs 52

#3 Solance   Members   -  Reputation: 100

Like
0Likes
Like

Posted 11 April 2005 - 03:07 PM

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

#4 MaulingMonkey   Members   -  Reputation: 1556

Like
0Likes
Like

Posted 11 April 2005 - 03:15 PM

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.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS