What’s the difference between istringstream, ostringstream and stringstream? / Why not use stringstream in every case?

Personally, I find it very rare that I want to perform streaming into and out of the same string stream. Usually I want to either initialize a stream from a string and then parse it; or stream things to a string stream and then extract the result and store it. If you’re streaming to and … Read more

How to read file content into istringstream?

std::ifstream has a method rdbuf(), that returns a pointer to a filebuf. You can then “push” this filebuf into your stringstream: #include <fstream> #include <sstream> int main() { std::ifstream file( “myFile” ); if ( file ) { std::stringstream buffer; buffer << file.rdbuf(); file.close(); // operations on the buffer… } } EDIT: As Martin York remarks … Read more

How to clear stringstream? [duplicate]

Typically to ‘reset’ a stringstream you need to both reset the underlying sequence to an empty string with str and to clear any fail and eof flags with clear. parser.str( std::string() ); parser.clear(); Typically what happens is that the first >> reaches the end of the string and sets the eof bit, although it successfully … Read more

stringstream, string, and char* conversion confusion

stringstream.str() returns a temporary string object that’s destroyed at the end of the full expression. If you get a pointer to a C string from that (stringstream.str().c_str()), it will point to a string which is deleted where the statement ends. That’s why your code prints garbage. You could copy that temporary string object to some … Read more

Why copying stringstream is not allowed?

Copying of ANY stream in C++ is disabled by having made the copy constructor private. Any means ANY, whether it is stringstream, istream, ostream,iostream or whatever. Copying of stream is disabled because it doesn’t make sense. Its very very very important to understand what stream means, to actually understand why copying stream does not make … Read more

How do you clear a stringstream variable?

For all the standard library types the member function empty() is a query, not a command, i.e. it means “are you empty?” not “please throw away your contents”. The clear() member function is inherited from ios and is used to clear the error state of the stream, e.g. if a file stream has the error … Read more

How to test whether stringstream operator>> has parsed a bad type and skip it

The following code works well to skip the bad word and collect the valid double values istringstream iss(“2.832 1.3067 nana 1.678”); double num = 0; while(iss >> num || !iss.eof()) { if(iss.fail()) { iss.clear(); string dummy; iss >> dummy; continue; } cout << num << endl; } Here’s a fully working sample. Your sample almost … Read more