c++stringstreamiomanipsetw

How to clear width when outputting from a stream, after using std::setw?


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?


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);