main() earlyreturn 0;" at the end of your program exits your
program. In fact, inside main you can stick a "return
0;" wherever you want and as often as you want, and it'll exit the
program.
For example, maybe you want to write a program that reads an
integer k from the user and writes out 1/k. If
the user enters zero, of course, there's a problem. Now we'll just
castigate the user and exit the program if he does that!
#include <iostream>
using namespace std;
int main()
{
// Get number from user
cout << "Enter a non-zero integer: ";
int k;
cin >> k;
// Deal with bad input
if (k == 0)
{
cout << "You really should read and follow the directions!" << endl;
return 1;
}
// Write out decimal approximation of 1/k
cout << "1/" << k << " is " << 1/double(k) << endl;
return 0;
}
You may prefer to use "exit(1)" instead of "return 1", since when we
eventually write code outside of the main() block "exit(1)" will still
exit the program, but "return 1" won't. The "exit" function is available
from the "iostream" library, for example.
1 + 5 + 3 + 48 + 32 =and prints out the resulting sum. This can be done nicely with a do-while
|
|
In case you don't find that compelling, here's another example.
Suppose we want to keep reading in ints from a list
until we read a negative number.
|
|
switch statementsswitch statement is a bit of a holdover from the C
language on which C++ is based, but it is something you'll probably see if
you look at a lot of programs. You use a switch statement
when you want to test a single variable or expression for several
different cases. The hitch is that the variable pretty much needs to
be an int or a char, which limits when
switch can be used. Switch breaks things up into cases. You
write
switch(expr)
{
... where expr is an expression of type int or
char, and then list cases consisiting of possible values of
expr. These cases must be constants, and each case is followed by a
:, then a sequence of statements to be executed, and finally a
break;. In other words, each case looks like this:
case constk:
stmt1
stmt2
...
stmtr
break;
You can list as many of these cases as you want. You can also put
default:
stmt1
stmt2
...
stmtr
break;
}
in as one "case". This is a catch-all that catches every situation in
which expr didn't match one of the other cases.
Here's an example program using
switch. It reads a date in "mm/dd/yyyy" format and
returns the date in "dd monthname, yyyy" format.
$ ./tree Enter height of tree: 10 * *** ***** ******* ********* *********** ************* *************** ***************** *******************The source code is given here.