I have a c_str which contains [51,53]. I want to split these pairs in two integers. They are in a c_str because I read them from an input file.
There must be an easy way to parse them. I was thinking of using the .at function:. But I am sure I made it way to complicated. Plus, it does not work, since it outputs:
pair: 0x7ffffcfc2998
pair: 0x7ffffcfc2998
etc
string pairstring = buffertm.c_str();
stringstream pair1, pair2;
int pairint1, pairint2;
pair1 << pairstring.at(1) << pairstring.at(2);
cout << "pair: " << pair1;
pair1 >> pairint1;
pair2 << pairstring.at(4) << pairstring.at(5);
//cout << "pair: " << pair2;
pair2 >> pairint2;
Any better ways to do this?
Something like this:
char c1, c2, c3;
int first, second;
std::istringstream iss(str);
if (iss >> c1 >> first >> c2 >> second >> c3
&& c1 == '[' && c2 == ',' && c3 == ']' )
{
// success
}
You might want to throw in an additional check to see if there are more characters after the closing bracket:
if ((iss >> std::ws).peek() != EOF) {
//^^^^^^^^^^^^^^
// eats whitespace chars and returns reference to iss
/* there are redundant charactes */
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With