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 the cin object and stores it in internal memory.
Syntax:
int num;
cout << "Please enter a number: ";
cin >> num;
A prompt (message) must be used to let the user know what data is to be entered.
The cout
object sends data to a standard output display device. It
is used
with the insertion operator (<<) to display information on the screen. You
can print any combination of literal constants, named constants, and variables.
cout << "Hello, World!";
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 will have the same output.
Escape sequences are special non-printing characters that control the printing behavior of
the output stream objects like cout
.
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 |
Real numbers can be displayed in either fixed-point or scientific notation:
Stream manipulators allow control over formatting:
Stream manipulator must appear in a cout
statement before the numbers you want
formatted
Example | Result (Display) |
---|---|
double total = 20535.75; |
20535.750000 |
double conversion = 4.9018436;
|
4.901844 |
double total = 20535.75; |
2.053575e+04 |
endl
manipulator and the newline
character
\n
?
setw()
manipulator in C++ when
printing data?
cin
and cin.get()
? In
what scenarios would you
use cin.get()
?
cin
expects an integer)? How can this be
handled in a
program?
Hello, World! Welcome to C++ programming.