C++ tutorial: else
'else' is a simple extension to 'if...'
The 'if' instruction allows the program to carry out certain actions if a particular
condition is true. Using 'else' you an specify additional actions to be carried out if the
condition is not true. The basic structure of the if...else instruction is as
follows:
if (condition)
{
statement1;
statement2;
}
else
{
statement3;
statement4;
}
Note that the layout of the program statements is designed to show which groups of statements
are executed when the condition is true (statements 1 and 2) and which when it is false
(statements 3 and 4). Strictly speaking, else is never strictly necessary; we can always
provide another 'if' with a different condition. However, there are many common-sense
situations where logic of the form 'if (something) then (do something) else (do something else)'
is appropriate.
Have a look at the program cin3.cpp. This program asks the user
to enter a number. If the number is valid is displayed, otherwise and error message is
produced.
The inputting of data is handled by the following two lines:
float n;
cin >> n;
Here 'n' is a real-number variable, and data is read into it from the keyboard using
'cin'. If this operation is successful, i.e., the user enters a valid number, then
'cin.good()' will be true:
if (cin.good())...
If it is true, the number is displayed using 'cout'. If not, an error message is produced.
The use of '.good()' is a standard and useful way of telling whether the last input or
output operation was a success or not. It applies equally well to reading and writing
disk files. Technically, '.good()' is an operation or
method that is applied to the object 'cin'.
|