Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

c++ - how to reuse stringstream

These threads do NOT answer me:

resetting a stringstream

How do you clear a stringstream variable?

std::ifstream file( szFIleName_p );
if( !file ) return false;

// create a string stream for parsing

std::stringstream szBuffer;

std::string szLine;     // current line
std::string szKeyWord;  // first word on the line identifying what data it contains

while( !file.eof()){

    // read line by line

    std::getline(file, szLine);

    // ignore empty lines

    if(szLine == "") continue;

    szBuffer.str("");
    szBuffer.str(szLine);
    szBuffer>>szKeyWord;

szKeyword will always contain the first word, szBuffer is not being reset. I can't find a clear example anywhere on how to use stringstream.

New code after answer:

...
szBuffer.str(szLine);
szBuffer.clear();
szBuffer>>szKeyWord;
...

Ok, thats my final version:

std::string szLine;     // current line
std::string szKeyWord;  // first word on the line identifying what data it contains

// read line by line

while( std::getline(file, szLine) ){

    // ignore empty lines

    if(szLine == "") continue;

    // create a string stream for parsing

    std::istringstream szBuffer(szLine);
    szBuffer>>szKeyWord;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...