Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a c_str

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?

like image 988
dorien Avatar asked Mar 19 '26 17:03

dorien


1 Answers

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 */
}
like image 170
jrok Avatar answered Mar 22 '26 07:03

jrok