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

C++ Extract number from the middle of a string

You can also use the built in find_first_of and find_first_not_of to find the first “numberstring” in any string. std::string first_numberstring(std::string const & str) { char const* digits = “0123456789”; std::size_t const n = str.find_first_of(digits); if (n != std::string::npos) { std::size_t const m = str.find_first_not_of(digits, n); return str.substr(n, m != std::string::npos ? m-n : m); } … Read more

how copy from one stringstream object to another in C++?

Indeed, streams are non-copyable (though they are movable). Depending on your usage, the following works quite well: #include <iostream> #include <sstream> int main() { std::stringstream ss1; ss1 << “some ” << 123 << ” stuff” << std::flush; std::stringstream ss2; ss2 << ss1.rdbuf(); // copy everything inside ss1’s buffer to ss2’s buffer std::cout << ss1.str() << … 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