4. Screen Output and Keyboard Input

Input and output were looked at briefly when the general form of a C++ program was discussed (see the What Do C++ Programs Look Like? section). It is now time to take a closer look at these topics.

Screen Output

PseudocodeFlowchart
Prompt user to enter a numberFlowchart symbol for input/output (a parallelogram), labeled 'Display total'

Our pseudocode and flowchart designs have frequently included steps which display information for the user to see. Two typical examples are given in the figure to the rightbelow. In each case the program is performing output to the screen.

PseudocodeFlowchart
Prompt user to enter a numberFlowchart symbol for input/output (a parallelogram), labeled 'Display total'

In C++, screen output is accomplished by using cout (pronounced “see-out”) statements. The general form of a cout statement is as follows (note that the square brackets, and everything between them, indicate an optional part of the statement:

std::cout << value1 [<< value2 ...];

The << symbol which follows std::cout is called the stream insertion operator. The value to display on the screen should come after this operator. For example, if the value of a variable is to be displayed, the name of the variable would appear where value1 is shown. Every cout statement must be followed by a semicolon.

Sometimes we need to display more than one value on the screen. A single cout statement can be used to display multiple values if we use the optional portion shown in the general form. Here are two examples of such cout statements, where the first displays a single value and the second three values:

std::cout << 123;
std::cout << "You owe " << total << ".";

The first statement displays the number 123 on the screen. The second statement displays the words “You owe ”, the value of the variable total, and a period. Note that the stream insertion operator is placed between each value to be displayed and that text is placed between double quotes.

It is best to label data values displayed to the screen so their meaning is clear. Output also often needs to be formatted. The next few sections discuss output formatting.

Newlines

Suppose the cout statements in previous example are used in a program with the goal of displaying 123 on one line on the screen and “You owe …” on the next line. As the code is written, all of the output would actually appear on the same line, with the ‘Y’ in “You” immediately following the ‘3’ in 123.

A newline can be used to place the next value displayed at the start of the following line on the screen (i.e., display the next information on a new line). A newline std::endl (it can also be written as a backslash immediately followed by an ‘n’ in quotation marks: "\n"). The corrected version of the cout statements is as follows:

std::cout << 123 << std::endl;
std::cout << "You owe " << total << std::endl;

The newline at the end of the first statement will have the desired result of moving the output from the second cout statement to the next line on the screen. Note that this newline could have instead been placed before "You owe ":

std::cout << 123;
std::cout << std::endl << "You owe " << total << std::endl;

Another newline was added to the end of the second cout statement to move the cursor to the next line after the period is displayed.

Multiple newlines can appear in a single statement if several blank lines are desired:

std::cout << std::endl << std::endl << std::endl;

Precision

When a program displays floating-point numbers (aka real numbers in math) it is often desirable to display them to a specific number of decimal places. For example, if a program displays a monetary value, say 4.50, two digits should be displayed after the decimal point. The default in C++, however, is to drop trailing zeros so 4.50 would appear as 4.5.

The number of digits which should appear after the decimal point, called the precision, can be set in a program. To do so, we use std::fixed and std::setprecision:

std::cout << std::fixed << std::setprecision(2)
          << "You owe " << total << std::endl;

Place an integer in parentheses after std::setprecision in a cout statement to set the precision. The integer should be zero or larger. In this example, the precision is set to two. Both std::fixed and std::setprecision must be used, in any order, before the floating-point value is displayed. Once a precision is set it remains set unless changed. If three additional floating-point values were subsequently displayed, all three would be displayed to two decimal places as well.

Note that the single cout statement is placed on two lines with the second line indented. This can be beneficial when the statement is too long to fit in a source code file without wrapping.

What would happen if the floating-point value to display has more digits after the decimal point than the precision allows? Suppose these two cout statements were now executed:

std::cout << 12.34715 << std::endl;
std::cout << 6.7829   << std::endl;

Since the precision is set to two, only two digits are going to be displayed after the decimal point. So the question really is, what happens to the extra digits? The answer depends upon the value of the digit after the one in the second position. In the first cout statement, 7 appears in the third position. Since it is greater than four, 12.347 will be rounded up to 12.35. Since 2, the third digit in the second statement, is less than five, it and any digits following it will be dropped (known as truncated in programming). If the precision had been set to three instead of two, the fourth digit in each number would determine what was displayed (12.347 and 6.783 in this case).

Both std::fixed and std::setprecision are from the C++ Standard Library, but different parts. The use of std::setprecision requires that another include statement be placed at the top of the program:

#include <iomanip>

Width

By default, the amount of screen space allotted to a displayed value is limited to what the value needs. For example, if “Hello” is displayed, space for five characters would be needed on the screen. If 47 is displayed, space for two characters would be needed. Sometimes, however, it is desirable to allot more space on the screen for a value than the value needs.

We can use std::setw (“set width”) to reserve a specific amount of space on the screen for a value:

std::cout << std::setw(5) << 38 << std::endl;
std::cout << 7 << std::endl;

The first statement results in 38 being allotted space on the screen for five characters. The number 38 is right justified within the allotted space (i.e.,   38). The width set by using std::setw only remains set until a value is displayed with all subsequent values allotted only the space they require. When the 7 in the second cout statement is displayed, it will be allotted one space on the screen (i.e., the space it needs). The width will also be reset if only a newline is used.

If the value to display requires more space than allotted by std::setw, the entire value will be displayed anyway with the space allotted for the value used first and the remainder of the value displayed to the right. For example, if 123 is displayed after std::setw(2) is used, the 1 and 2 will be placed in the two spaces allotted by std::setw and then the 3 displayed.

Like std::setprecision, use of std::setw also requires that “#include <iomanip>” be placed at the top of the program.

Keyboard Input

PseudocodeFlowchart
Read numberFlowchart symbol for input/output (a parallelogram), labeled 'Input quantity'

Our pseudocode and flowchart designs have also frequently included steps which read data typed by the user. Two typical examples are given in the figure to the rightbelow. In each case the program is performing input from the keyboard.

PseudocodeFlowchart
Read numberFlowchart symbol for input/output (a parallelogram), labeled 'Input quantity'

In C++, keyboard input is accomplished by using cin (pronounced “see-in”) statements. A cin statement is used to read a single value into a variable:

std::cin >> variable;

The >> symbol that follows std::cin is called the stream extraction operator. The variable to read the value into should be placed after this operator. Every cin statement must be followed by a semicolon.

For example, suppose the user is to enter a number which will be stored in a variable named number. The following cin statement could be used to accomplish this action:

std::cout << "Please enter a number: ";
std::cin >> number;

Each time a program needs the user to enter a value, the program should ask the user to do so. The request by a program for the user to enter a value is sometimes called a prompt. Well-chosen words used for the prompt will help the user understand the type of value needed by the program. The example above asks the user to enter a generic number which the cin statement then reads.

If this code was executed, the prompt would be displayed and then the program would pause at the cin statement until the user typed a value and pressed Enter. It is the act of pressing Enter which causes execution of the program to continue.

The data type of the variable used in a cin statement determines the type of value which can be successfully read by the program. For the cin statement above, only integer values could be read if number is declared as an integer. If the user types, for example, an ‘x’ instead of an integer value, the program would not be able to store the letter into the number variable. As a result, the read would fail and the variable would not be given a value. Execution of the program would continue, but there would most likely be problems when it tried to use the value of the variable.

A Sample Program

The program below ties the output formatting and input topics together into a single example. The program reads three values and then displays them on the screen:

// Program    : format_output.cpp
// Author     : A. Student
// Due Date   : September 9, 2025
// Description: This program asks the user to enter a
//              letter, integer and real number and then
//              displays the values entered.

#include <iomanip>
#include <iostream>

int main()
{
    char letter;        // stores letter entered by user
    int integer;        // integer entered by user
    float real_number;  // real number entered by user

    std::cout << "Please enter a letter: ";
    std::cin >> letter;

    std::cout << "Please enter an integer: ";
    std::cin >> integer;

    std::cout << "Please enter a real number: ";
    std::cin >> real_number;

    std::cout << std::endl;
    std::cout << "  Values Entered" << std::endl
    std::cout << std::endl;

    std::cout << "Letter: " << std::setw(10) << letter
              << std::endl
    std::cout << "Integer: " << std::setw(9) << integer
              << std::endl;
    std::cout << std::fixed << std::setprecision(1);
    std::cout << "Real Number: " << std::setw(5) << real_number
              << std::endl

    return 0;
}

The placement of the “#include <iomanip>” statement is shown in the example. It is only included once although required for the use of std::setprecision and std::setw.

The first three cout statements prompt the user to enter each of the three values. The remaining four cout statements display the program’s formatted output. Each of these four statements display data for a single line on the screen. Taking this approach can make a program easier to understand.

A sample run of the program (Why is it named formatoutput.exe?) appears below. The prompts to the user, the values typed by the user (in bold), and the program’s final output are all included:

Please enter a letter: z
Please enter an integer: 43
Please enter a real number: 2.7

  Values Entered

Letter:          z
Integer:        43
Real Number:   2.7

Since most users would tend to use the term “real number” instead of “floating-point number”, the program uses “real number” when interacting with the user.

Because of the precision used, any floating-point value entered will be displayed with a single digit after the decimal point.

One question which may have come to mind when std::setw was discussed is why would we want to allot more space on the screen for a value than it actually needs? An answer is demonstrated by this program. When the values typed by the user are displayed by the cout statements, they are displayed in a right justified column. As long as the user provides integer and floating-point values smaller than the width values used in std::setw, this will be true. So std::setw is being used to allocate a fixed amount of space for each value, while the lengths of the values vary, resulting in an aligned column of values. The different width values used in the code are due to the different lengths of the text used to label each value.