I want to be able to build a string from a class that I create that derives from Stream. Specifically, I want to be able to write code like this:
void Print(Stream stream) {     // Some code that operates on a Stream. }  void Main() {     StringStream stream = new StringStream();     Print(stream);     string myString = stream.GetResult(); }   Can I create a class called StringStream that makes this possible? Or is such a class already available?
Update: In my example, the method Print is provided in a third-party external DLL. As you can see, the argument that Print expects is a Stream. After printing to the Stream, I want to be able to retrieve its content as a string.
StringStream in C++ is similar to cin and cout streams and allows us to work with strings. Like other streams, we can perform read, write, and clear operations on a StringStream object. The standard methods used to perform these operations are defined in the StringStream class.
A stringstream associates a string object with a stream allowing you to read from the string as if it were a stream (like cin). To use stringstream, we need to include sstream header file. The stringstream class is extremely useful in parsing input.
A stringstream class in C++ is a Stream Class to Operate on strings. The stringstream class Implements the Input/Output Operations on Memory Bases streams i.e. string: The stringstream class in C++ allows a string object to be treated as a stream. It is used to operate on strings.
Very Informally: A string is a collection of characters, a stream is a tool to manipulate moving data around. A string stream is a c++ class that lets you use a string as the source and destination of data for a stream.
You can use tandem of MemoryStream and StreamReader classes:
void Main() {     string myString;      using (var stream = new MemoryStream())     {         Print(stream);          stream.Position = 0;         using (var reader = new StreamReader(stream))         {             myString = reader.ReadToEnd();         }     } } 
                        Since your Print() method presumably deals with Text data, could you rewrite it to accept a TextWriter parameter?
The library provides a StringWriter: TextWriter but not a StringStream.  I suppose you could create one by wrapping a MemoryStream, but is it really necessary?
After the Update:
void Main()  {   string myString;  // outside using    using (MemoryStream stream = new MemoryStream ())   {      Print(stream);      myString = Encoding.UTF8.GetString(stream.ToArray());   }   ...   }   You may want to change UTF8 to ASCII, depending on the encoding used by Print().
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