I have a function recieving a string, which is a pair of comma delimited integers in a fashion such as \"12,4\". How can I parse the integers out of this string?
Depends whether or not you can depend on the incoming data being valid. If you can, I'd do:
#include <cstdlib>
#include <utility>
#include <string>
std::pair<int, int> split(std::string const& str)
{
int const a = std::atoi(str.c_str());
int const b = std::atoi(str.c_str() + str.find(',') + 1);
return std::make_pair(a, b);
}
if you use Qt, you can use QString::split();
std::getline
implements the basic "split" functionality (I don't see it mentioned in the first few answers at the other question.)
vector< int > numbers;
istringstream all_numbers_iss( "12,4" );
string number_str;
int number;
while ( getline( all_numbers_iss, number_str, ',' ) // separate at comma
&& istringstream( number_str ) >> number ) {
numbers.push_back( number );
}
boost tokenizer works pretty well. Click here for example.