how to reuse stringstream

守給你的承諾、 提交于 2019-12-01 03:04:06
Marcus Riemer

You didn't clear() the stream after calling str(""). Take another look at this answer, it also explains why you should reset using str(std::string()). And in your case, you could also reset the contents using only str(szLine).

If you don't call clear(), the flags of the stream (like eof) wont be reset, resulting in surprising behaviour ;)

It depends what you're doing with it. It's generally easier to just create a new istringstream or ostringstream. To "reset" a stream, you have to clear its buffer, clear any error flags, reset any formatting flags, plus the precision and fill, reimbue it with the original locale, and not forget any extended formatting information generated with a value returned from xalloc. In sum, impossible to get correct.

And while I'm at it, your loop is wrong, and will probably result in the last line being processed twice. file.eof() only has a usable meaning after the input has failed (and even then, it's not 100% reliable). What you want is:

std::string line;
while ( std::getline( file, line ) ) {
    if ( !line.empty() ) {
        std::istringstream buffer( line );
        //  ...
    }
}

(Actually, you probably want to trim trailing white space from the line before the test for empty.)

In most cases, it is easier to create a new istringstream or ostringstream instead of resetting the same ones.

However, if you do want to resent them:

  • Resent flags of the stream (to avoid unexpected behavior) using clear ().

  • While you can correct the contents of your stringstream using str (""), for efficiency purposes we might prefer str(std::string()).

ss is stringstream. Use

  • first step: ss.clear();
  • second step: ss.str("");

to reuse the stringstream -- completely clear the string stream.

If you have the stream in a class member, use unique_ptr<stringstream>, then just reset(new stringstream(...)) to reuse it.

Imagine a config file.

par1=11
par2=22

codes:

std::string line, strpar1, strpar2;
int par1, par2;
std::ifstream configfile("config.cfg");

std::getline(configfile, line);    // first line to variable "line"
std::istringstream sline(line);
while (std::getline(sline, strpar1, '='));
par1 = std::stoi(strpar1);  // par1 get 11

bool b = sline.eof(); // true

std::getline(configfile, line);    // second line to variable "line"
sline.clear();    //
sline.str(line);    // reuse "sline"

b = sline.good();  // true  // goodbit is zero, indicating that none of the other bits is set.
b = sine.fail();  // false
b = sline.bad();  // false
b = sline.eof(); // false

while (std::getline(sline, strpar2, '='));
par2 = std::stoi(strpar2);  // par2 get 22

goodbit is zero, indicating that none of the other bits is set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!