Streams

Input and output in C++ is based on the concept of a stream. A stream is a sequence of bytes that flow from something to something else. The process of output involves moving bytes, one at a time, from a program to a device. This device could be a monitor, a printer, or even a file on a hard drive. Input is the opposite. Input involves the flow bytes from a device (a keyboard, a file, a network connection) into the program.

1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: #include <string>#include <cstdlib>#include <iostream> using namespace std; int main(int argc, char* argv[]) { cout << "Enter your name: "; string name; cin >> name; cout << "Hello " << name; return EXIT_SUCCESS;}
Listing 1 Stream based output

Listing 1 is a simple example of stream based input and output. The above code first streams data (the characters in the text string "Enter your name: ") from the program to a device (the console) in line 9. Stream based output operations use the << operator to indicate the data to write to the stream. The stream used in this line is the output stream referenced by object cout. This object is of type ostream, which is short for "output stream."

The program in Listing 1 then streams data from the keyboard into the program, storing the user entered text in the variable name. Stream input operations use the >> operator to specify the variable where the program should place the data it reads from the stream. The stream used in this line is the input stream referenced by object cin. The cin object is of type istream, which is short for "input stream." The listing then again streams output to the console. In line 14, we see that we can place more than one piece of data into the stream in one statement.

We can open and use streams to read and write data to and from many devices besides the console. For example, a program can use a file output stream to write data to the file system. Network communication through sockets is also stream based.