Question

I'm using a std::stringstream to parse a fixed format string into values. However the last value to be parsed is not fixed length.

To parse such a string I might do:

std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag
   >> sLeftovers;

But how do I set the width such that the remainder of the string is output?

Through trial and error I found that doing this works:

   >> std::setw(-1) >> sLeftovers;

But what's the correct approach?

Was it helpful?

Solution

Remember that the input operator >> stops reading at whitespace.

Use e.g. std::getline to get the remainder of the string:

std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag;
std::getline(ss, sLeftovers);

OTHER TIPS

std::setw only affects exactly one operation, i.e. >> bFlag will reset it to default, so you don't need to do anything to reset it.

i.e. your code should just work

std::stringstream ss("123ABCDEF1And then the rest of the string");
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag
   >> sLeftovers;

Try this:

std::stringstream ss("123ABCDEF1And then the rest of the string");
std::stringstream::streamsize initial = ss.width(); // backup
ss >> std::setw(3) >> nId
   >> std::setw(6) >> sLabel
   >> std::setw(1) >> bFlag
   >> sLeftovers;

ss.width(initial); // restore

I'm surprised that setw(-1) actually works for you because I haven't seen this documented, and when I tried your code on VC10, I only got "And" for sLeftovers. I'd probably use std::getline( ss, sLeftovers ) for the remainder of the string, which worked for me in VC10.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top