how to reuse stringstream

前端 未结 6 1189
遇见更好的自我
遇见更好的自我 2021-01-03 22:12

These threads do NOT answer me:

resetting a stringstream

How do you clear a stringstream variable?

        std::ifstream file( szFIleName_p )         


        
6条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-03 22:41

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

提交回复
热议问题