The Standard C++ Library
Streams
Streams are used in C++ programs to send data from one place in memory to another. For example, the output stream takes text from your program and prints it to the screen. Similar operations can print to a file, to a string in memory, or across a network. This chapter will be limited to text streams only.
Using C++ Streams
To use the streams in your program, you must include the following header files:
#include#include
Standard Streams
The C++ library provides three standard streams to enter text into your program and to output text from it. "cout" is the standard output stream, and is used to print out text to the screen. For instance,
cout << "Hello World" << endl;
will print "Hello World" to the screen and go to the next line. The "<<" symbol means that the data after it will be sent to the stream. Other data besides strings can be sent to the stream:
int year = 2260; cout << "The year is " << year << endl;
This example will print out the correct year. This is very useful if you don’t have a clock handy. Note the use of "endl" at the end of the command. This tells the stream to go to the next line. You can also use "ends" to leave the stream at the end of the line and pick up again there in the next stream command. Another stream is "cerr" which works exactly the same way as "cout" except that the output is assumed to be an error message. You can use this to print error messages within your program. The third standard stream is "cin" which allows you to receive text entered into your program. This stream is used differently from the output streams. For example to receive a number, you must give the command:
int a_number; cin >> a_number;
The input and output streams can be used together to provide user interaction. For example, this program:
int ssn;
cout << "Please enter your social security number now: " << ends;
cin >> ssn;
cout << endl;
will allow your to find out things about your friends that you never knew before…
File Streams
The library provides methods to easily read from and write to a file. The stream for reading in from a file is called an ifstream and is used like this:
ifstream file_in("goober.txt");
The "file_in" stream can then be used to read any data from the file "goober.txt". This stream can be used the same way as "cin". To write to a file, create a stream the same way:
ofstream file_out("goober.txt");
and use it like "cout".