I'm trying to read an entire stream (multiple lines) into a string.
I'm using this code, and it works, but it's offending my sense of style... Surely there's an easier way? Maybe using stringstreams?
void Obj::loadFromStream(std::istream & stream) { std::string s; std::streampos p = stream.tellg(); // remember where we are stream.seekg(0, std::ios_base::end); // go to the end std::streamoff sz = stream.tellg() - p; // work out the size stream.seekg(p); // restore the position s.resize(sz); // resize the string stream.read(&s[0], sz); // and finally, read in the data.
const
reference to a string would do as well, and that may make things easier... const std::string &s(... a miracle occurs here...)
Read whole ASCII file into C++ std::string txt using file object f of ifstream type to perform read operation. Declare a variable str of string type. If(f) Declare another variable ss of ostringstream type. Call rdbuf() fuction to read data of file object.
Other ways to read a std::istreamTo read a line of input, try the getline() function. For this, you need #include <string> in addition to #include <iostream> . To read a single char: use the get() method. To read a large block of characters, either use get() with a char[] as the argument, or use read() .
Use rdbuf to Read File Into String in C++ The rdbuf function is a built-in method to return a pointer to the stream buffer of the file, which is useful to insert the entire contents of the file using the << operator to the needed object.
What Is the StringStream Class? 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.
How about
std::istreambuf_iterator<char> eos; std::string s(std::istreambuf_iterator<char>(stream), eos);
(could be a one-liner if not for MVP)
post-2011 edit, this approach is now spelled
std::string s(std::istreambuf_iterator<char>(stream), {});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With