Extending the Basic Streams in C++ - The Source of it All
(Page 2 of 4 )
First, let me tell you that there are three types of streams in C++, namely the fstream (for file I/O), the sstream (for C type character sequences - char*- however this is a leftover from the days of C++ standardization for compatibility reasons and should not be used, as support for this in the future may be removed; this isn't a template class) and strstream (for the string type of the STL library). Now all of these will have in common the fact that the text stored eventually is a text. That is why the following code snippet succeeds in execution:
#include <iostream>
#include <sstream>
#include <strstream>
using namespace std;
char alfa = 'A';
template < typename _S>
std::basic_ostream<_S>& fillWithText (std::basic_ostream<_S>& stream)
{
stream << "Filled with text the " << alfa++ << "Stream"<< std::endl;
return stream;
}
int main()
{
wostringstream A;
wostream& B = std::wcout;
fillWithText<wchar_t>(A);
std::wcout << A.str();
fillWithText<wchar_t>(B);
}
Moreover, the result is:
Filled with text the A Stream
Filled with text the B Stream
Press any key to continue . . .
First, let's point out that you can assign a string to the standard input/output, and in the future thread it just as the cout stream class. Second, look at the way we printed the A stream. The str() function returns a pointer to the character sequence inside the stream itself, though it will print all that we put inside it in the meantime.
The existence of this pointer can be reduced to the inside representation of a stream. The streambuff class handles this. A schematic representation looks like the figure below.

Next: The streambuff Class >>
More C++ Articles
More By Gabor Bernat