c++ parse int from string
You can use istringstream
.
string s = "10";
// create an input stream with your string.
istringstream is(str);
int i;
// use is like an input stream
is >> i;
You can use boost::lexical_cast:
#include <iostream>
#include <boost/lexical_cast.hpp>
int main( int argc, char* argv[] ){
std::string s1 = "10";
std::string s2 = "abc";
int i;
try {
i = boost::lexical_cast<int>( s1 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
try {
i = boost::lexical_cast<int>( s2 );
}
catch( boost::bad_lexical_cast & e ){
std::cout << "Exception caught : " << e.what() << std::endl;
}
return 0;
}
There is no "right way". If you want a universal (but suboptimal) solution you can use a boost::lexical cast
.
A common solution for C++ is to use std::ostream
and << operator
. You can use a stringstream
and stringstream::str()
method for conversion to string.
If you really require a fast mechanism (remember the 20/80 rule) you can look for a "dedicated" solution like C++ String Toolkit Library
Best Regards,
Marcin
In C++11, use
std::stoi
as:std::string s = "10"; int i = std::stoi(s);
Note that
std::stoi
will throw exception of typestd::invalid_argument
if the conversion cannot be performed, orstd::out_of_range
if the conversion results in overflow(i.e when the string value is too big forint
type). You can usestd::stol
orstd:stoll
though in caseint
seems too small for the input string.In C++03/98, any of the following can be used:
std::string s = "10"; int i; //approach one std::istringstream(s) >> i; //i is 10 after this //approach two sscanf(s.c_str(), "%d", &i); //i is 10 after this
Note that the above two approaches would fail for input s = "10jh"
. They will return 10 instead of notifying error. So the safe and robust approach is to write your own function that parses the input string, and verify each character to check if it is digit or not, and then work accordingly. Here is one robust implemtation (untested though):
int to_int(char const *s)
{
if ( s == NULL || *s == '\0' )
throw std::invalid_argument("null or empty string argument");
bool negate = (s[0] == '-');
if ( *s == '+' || *s == '-' )
++s;
if ( *s == '\0')
throw std::invalid_argument("sign character only.");
int result = 0;
while(*s)
{
if ( *s < '0' || *s > '9' )
throw std::invalid_argument("invalid input string");
result = result * 10 - (*s - '0'); //assume negative number
++s;
}
return negate ? result : -result; //-result is positive!
}
This solution is slightly modified version of my another solution.