3.4 Keyboard and monitor 61
False read
Consider the followingwhileloop calculating the square of a typed inte-
ger:
int a;
while (cin >> a)
{
int a2 = a*a;
}
Thewhileloop will be executed repeatedly as long as an integer is supplied from
the keyboard, and will be exited if a character or a non-integer (real) number is
entered, amounting to afalse read. The reason is that thecinfunction returns
to the program a Boolean variable that is true (1) in the case of successful
input, and false (0) in the case of unsuccessful input.
The single false read can be generalized to multiple false reads. For exam-
ple, the following code reads two variables and quits when inappropriate input
is entered:
int a;
float b;
while(cin>>a && cin>>b)
{
cout << a <<""<<b<<endl;
}
Later in this section, we shall discuss ways of clearing the false read.
Displaying on the monitor
To display the value of a numerical variable on the monitor, we issue the
command:
cout << variable;
To display the value of a numerical variable and move the cursor to the next
line, we use:
cout << variable << "\n";
To print a message on the screen and move the cursor to the next line, we use:
cout << "hello\n";