Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to reuse stringstream

Tags:

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; 
like image 491
Icebone1000 Avatar asked Aug 24 '12 15:08

Icebone1000


People also ask

How do you flush a Stringstream?

For clearing the contents of a stringstream , using: m. str("");

Can you return a Stringstream?

You can't return a stream from a function by value, because that implies you'd have to copy the stream.

Is Stringstream deprecated?

strstream has been deprecated since C++98, std::stringstream and boost::iostreams::array are the recommended replacements.

What is the use of Stringstream?

The StringStream class in C++ is derived from the iostream class. Similar to other stream-based classes, StringStream in C++ allows performing insertion, extraction, and other operations. It is commonly used in parsing inputs and converting strings to numbers, and vice-versa.


1 Answers

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

like image 56
Marcus Riemer Avatar answered Sep 16 '22 14:09

Marcus Riemer