Programming C++  «Prev  Next»
Lesson 2Output
Objective Examine simple output of a C++ program.

C++ Program Output

Programs must communicate to be useful. Let us look at a C++ program that prints the phrase C++ is an improved C onscreen.
Program dissection
Move your mouse cursor over the highlighted lines of code below to receive tooltip information of their function.
C++ Output
Rewriting the program
While the above program is correct, we can simplify the program as follows:
//A first C++ program illustrating output
#include <iostream.h>
int main()
   cout << "C++ is an improved C." << endl;
   return (0);
We use the put to operator (<<) twice with cout. Each time we use << with cout, printing continues from the position where it previously left off.
The identifier endl flushes the output stream and adds a new line. The endl identifier is called a manipulator.
A manipulator is a value or function that has a special effect on the stream it operates on. For a complete list of C++ I/O manipulators, click the Help button on the toolbar.

Use output redirection to capture program output in a file.
Consider the program that computes the average value of an input sequence. If you use such a program, then it is quite likely that you already have the values in a file, and it seems a shame that you have to type them all in again. The command line interface of your operating system provides a way to link a file to the input of a program, as if all the characters in the file had actually been typed by a user. If you type
average < numbers.txt
the program is executed. Its input instructions no longer expect input from the keyboard.
All input commands get their input from the file numbers.txt. This process is called input redirection. Input redirection is an excellent tool for testing programs. When you develop a program and fix its bugs, it is boring to keep entering the same input every time you run the program. Spend a few minutes putting the inputs into a file, and use redirection. You can also redirect output. In this program, that is not terribly useful. If you run
average < numbers.txt > output.txt
the file output.txt contains a single line such as Average: 15.
However, redirecting output is obviously useful for programs that produce lots of output. You can print the file containing the output or edit it before you turn it in for grading