The cout (pronounced as see out) object is an output object that sends data to a standard output display device. It is used with the insertion operator (<<) to display information on the screen. Information that is sent to the screen can be any combination of literal constants, named constants, and variables.
Following is a syntax for writing a cout statement, note that the part in square brackets is optional which can be used to print multiple items in the same statement:
Syntax:A stream manipulator is used to manipulate (manage) the characters in an input or output string. endl is a stream manipulator that moves the cursor to the next line on the screen. It's the same as pressing the Enter key on the keyboard, as shown in Figure 3.2. Figure 3.3 shows combining cout statements (the cout from line 7 and the semicolon at the end of line 6 from Figure 3.2 is removed). Note that both with have the same output.
The escape sequences are special non-printing characters that are used to control the printing behaviour of the output stream objects (such as ‘cout’). The escape sequences and the characters they represent are given in Table 3.1:
Escape sequence | Character represented |
---|---|
\a | Alert (bell, alarm) |
\b | Backspace |
\f | Form feed (new page) |
\n | New-line |
\r | Carriage return |
\t | Horizontal tab |
\v | Vertical tab |
\’ | Single quotation mark |
\” | Double quotation mark |
\? | Question mark |
\\ | Backslash |
Example | Result (Display) |
---|---|
double total = 20535.75; cout << fixed; cout << total << endl; |
20535.750000 |
double conversion = 4.9018436; cout << fixed << conversion << endl; |
4.901844 |
double total = 20535.75; cout << scientific << total << endl; |
2.057575e+04 |
C++ uses stream (sequence of characters) objects to perform input/output operations. The cin object is used to get data from the keyboard. The program pauses while the user enters data. The extraction operator (>>) takes information out of cin object and stores it in internal memory
Syntax:A prompt (message) must be used to let the user know what data is to be entered.
Example 1 | Example 2 | Example 3 |
---|---|---|
int num; cout << “Please enter a number: ”; cin >> num; |
double height; cout << “Please enter height: ”; cin >> height; |
char response; cout << “Please enter y or n: ”; cin >> response; |