The stream classes

A stream is a facility that allows us to use various input and output devices more or less uniformly. There are a number of variants of this data type, which are related by inheritance so that we can substitute a more highly specialized variant for a more basic one. So far we've encountered istream, ostream, ifstream, ofstream, and of course most recently stringstream. The best place to start a further investigation of this family of classes is with one of the simplest types, an ostream. We've used a predefined object of this type, namely cout, quite a few times already. To see a little bit more about how this works, take a look at the program in Figure 9.15.

Figure 9.15. A simple stream example (codestream1.cpp)
#include <iostream>
using namespace std;

int main()
{
    short x;
    char y;

    x = 1;
    y = 'A';

    cout << "Test " << x;
    cout << " grade: " << y;
    cout << endl;

    return 0;
}

When the program starts, cout looks something like Figure 9.16.

Figure 9.16. An empty ostream object


What is the purpose of the buffer and the put pointer?[20] Here's a breakdown:

[20] Please note that the type of the put pointer is irrelevant to us, as we cannot ever access it directly. However, you won't go far wrong if you think of it as the address of the next available byte in the buffer.

  1. The buffer is the area of memory where the characters put into the ostream are stored.

  2. The put pointer holds the address of the next byte in the output area of the ostream — that is, where the next byte will be stored if we use << to write data into the ostream.

At this point, we haven't put anything into the ostream yet, so the put pointer is pointing to the beginning of the buffer. Now, let's execute the line cout << "Test " << x;. After that line is executed, the contents of the ostream look something like Figure 9.17.

Figure 9.17. An ostream object with some data


As you can see, the data from the first output line has been put into the ostream buffer. After the next statement, cout << " grade: " << y;, is executed, the ostream looks like Figure 9.18.

Figure 9.18. An ostream object with some more data.


Now we're ready for the final output statement, cout << endl;. Once this statement is executed, the ostream looks like Figure 9.19.

Figure 9.19. An empty ostream object


By now, you're probably wondering what happened to all the data we stored in the ostream. It went out to the screen because that's what endl does (after sticking a newline character on the end of the buffer). Once the data has been sent to the screen, we can't access it anymore in our program, so the space that it took up in the buffer is made available for further use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset