I have a vector of strings. Need help figuring out how to convert it into vector of integers in order to be able to work with it arithmetically. Thanks!
#include
Use boost::lexical_cast
. And surround it with try-catch
block.
try
{
for (size_t i=0; i(vectorOfStrings[i]));
}
}
catch(const boost::bad_lexical_cast &)
{
//not an integer
}
Or you can use Boost.Spirit
parser (which someone claims is faster than even atoi()
) as:
int get_int(const std::string & s)
{
int value = 0;
std::string::const_iterator first = s.begin();
bool r = phrase_parse(first,s.end(),*int_[ref(value)=_1], space);
if ( !r || first != s.end()) throw "error";
return value;
}
//Usage
int value = get_int("17823");
std::cout << value << std::endl; //prints 17823
The full demo using your code : http://ideone.com/DddL7