Ch 3: Doing Things! - C++ by Metrowerks
Introduction to C++ by Metrowerks
Introduction to the Input/Output System
Now that you know how to create variables, you need to know how to print things to the screen and get input from a user and store it into a variable. There are a few ways to do this, and lots of ways to make special things happen. We'll get to all the special conditions in a later lesson, but right now, we'll cover snagging simple pieces of data from the keyboard and writing simple messages to the screen.
Introduction to the Input and Output Header
The name of the I/O header file (iostream) leads us to our first topic: streams.
A stream is the flow of data to or from one place to another. This may be a physical item such as the hard drive file, or it may be an area in memory.
There are two modes of streams that the C++ I/O system includes: text streams, which are used with characters, and binary strings, which can be used with any type of data. Text streams sometimes translate characters, such as the \n character. Some types of streams operate on data stored in files.
Predefined Stream Objects
We have been using two predefined I/O stream objects throughout this course: the standard input steam (cin), and the standard output stream (cout). There are two stream objects linked to standard output that are generally used with abnormal errors during a program execution: cerr and clog. Using cerr leads to an immediate output, much like the cout object. The clog object is buffered, and only outputs when the buffer is full.
|cerr||Console error output||Screen|
Table 3-1: Some of C++'s Predefined Streams.
|clog||Buffered version of cerr||Screen|
We discussed wide characters at the beginning of this course. These are generally used for languages such as Chinese that require large character sets. The standard wide character streams are wcin, wcout, wcerr, and wclog.
These standard input and output streams are generally the monitor and keyboard. However, they may be redirected to other files and devices, local or remote.
Input and Output Member Functions
Using put() and get() are quite simple. You will see that they are overloaded for many various uses. First, a simple character example is examined.
These are the prototypes for put() and get().
istream &get(char &ch);
ostream &put(char ch);
The get() member function reads a single character from the stream and puts it into the character ch, and returns a reference to the stream. The put() function writes to character ch and returns the stream. For example,
will read one character from the console input device.
In addition to the single character form of get(), the function is overloaded in several ways. The two most common forms are:
istream &get(char *buf, int num, char delim = '\n');
The first overloaded function reads characters into a stream until either the num of characters is reached, the specified deliminator is reached, or it runs out of characters. The array pointed at by buf will be null terminated. The deliminator is not extracted. It is left in the stream until the next input operation.
The second form get() without any parameters returns the next character from the stream. In AT&T standard C++ it returns EOF if end-of-file is encountered. It is similar to standard C's getc() function.
Another member function that performs input is getline(). Its prototype is:
istream &getline(char *buf, int num, char delim = '\n');
As you can see, this function is identical to the overloaded get() function; however, the difference is that getline() reads and removes the deliminator (newline) from the input stream.
using namespace std;
const int strLength = 255;
cout << "Enter your first name middle name and last name\n> ";
cout << "Your name is \n" << strn << "\n";
Enter your first name middle name and last name
> Bad Bad LeRoy Brown
Your name is
Bad Bad LeRoy Brown
Introduction to Functions
You have now seen the setup of a basic program in C++. We'll now begin studying some of the basic elements of a C++ program. First, we'll take a quick look at functions -- the building blocks of a program. We'll then examine how to instruct a program to output text to the screen. Finally, we'll discuss two simple commands that we'll build on throughout this course: if and for.
As discussed earlier, a C++ program is built from one or more functions. A function is a subroutine that contains one or more statements and performs one or more tasks. However, it's best to have each function perform only one task. Remember that each function must be named and each function must be called by its name. A function can be given almost any name (as long as it doesn't begin with a number), but the function that begins the execution of any program must be main(). There are two types of functions that can be used in a C++ program: functions written by the programmer and prewritten functions from the standard library or a library provided by the vendor or third party. Standard library functions are implemented by the compiler vendor. We'll now examine a program with two functions to see how each works. Before reading the description of the program, study the code and try to determine what the program will output:
/* A 2-function program
function #1: main()
function #2: lamb()
using namespace std;
void lamb(); //declaration (prototype) of the lamb() function
cout << "Mary had a little ";
lamb(); //This calls the function lamb()
cout << ", its fleece as white as snow.";
cout << "lamb";
Notice that the lamb() function had to be declared before it could be executed. This declaration lets the computer know the return type of the function. In this case, the return type is void; the function will not return a value. The program begins by executing the main() function. This function begins with an output. The main() function then calls the lamb() function, which outputs more text. Finally, the main() function contains one more output command, then returns the value of 0 and terminates. The output for the program looks like this:
Mary had a little lamb, its fleece as white as snow.
The if, for, and switch Control Statements
What good is a program if it can't make some decisions on its own? Control statements allow you to set up conditions so that your program can make choices and execute operations in the proper way. With if, for, and switch statements, you can create conditionals and loops to make your program more intelligent.
The if Statement
if (expression) statement;
The if statement will be executed if the condition associated with it is true or non-zero. Conversely, the statement will not be executed if the condition is false or zero. For example, the following sample line of code will display output (since the condition is true):
if (5 > 3) cout << "Twinkle, Twinkle little star";
In this sample line of code, however, the output will not be displayed:
if (3 > 5) cout << "How I wonder what you are";
As you can see, the condition (3 > 5) is false. This fallacy prevents the execution of the if statement. Now take a look at the if statement in action:
/* Sample Program
Illustration of the if statement
using namespace std;
int x, y;
cout << "Please enter a number: ";
cin >> x;
cout << "Now enter a smaller number: ";
cin >> y;
if (y < x) cout << "Thank you, that is correct.";
If the second number is indeed smaller than the first, the program will output:
Thank you, that is correct.
However, if the first number is smaller than the second, there will be no output. A two-way if statement is as follows:
if (expression) statement; else statement;
If the expression is non-zero, or true, the first statement is executed. If the expression is zero, or false, then the second else statement is executed.
Also, if statements can occur within other if statements. Statements within other statements are called nested statements. The following is an example of a nested if statement:
if ((expression-1) || (expression-2)) statement;
In this example, either or both of the expressions must be true for the statement to be executed. Here is another example of how if statements can be nested:
In this example, if expression-1 is true, statement-1 is executed. If expression-1 is false, then expression-2 is evaluated. If expression-2 is true, then only statement-2 is executed. If expression-2 is false, the entire block of code is ignored.
The for Statement
The general for statement is set up as follows:
for (intializationstatement; expression-1; expression-2;)
In this case, the loop is initialized with the first statement. The first expression usually specifies a test executed before each iteration of the loop (the loop will end if the value of expression-1 becomes zero, or false). The second expression specifies the increment by which the expression is modified with each time the loop repeats. The last statement is the actual process that takes place during each iteration of the loop.
The following sample program will output all the odd numbers from 1 through 99:
/* Sample Program
Illustration of the for loop
using namespace std;
int oddnumbers; //Control variable
for (oddnumbers=1; oddnumbers<100; oddnumbers=oddnumbers+2)
cout ><< oddnumbers << " ";
In this example, initialization sets the control variable to the value of 1 (an odd number). The condition is that all numbers must be less than 100. The increment by which the numbers increase is 2. Therefore, when the statement is executed, the output will display all odd numbers from 1 through 99.
The switch Statement
Depending on the value of an expression, control can be transferred to one or more of several statements by using a switch statement. A general switch statement is created like this:
case value-1: statement-1; break;
case value-2: statement-2; break;
The value of the expression is checked against each case value until there is a match or the expression reaches the default. A switch expression is stopped when break is reached.
Using while and do-while Loops; continue, break, goto, and Nested Loops
I hope by this point that you are seeing the power of the control statement. These statements allow the program to make decisions based on the values of certain variables. Other control statements repeat a task a specified number of times or at times that a certain condition is true. We will now examine while loops and tackle some issues relating to control statements.
The while Statement
The expression in a while statement must meet the same criteria as those of an if statement: the expression must be arithmetic, pointer, or class type. The expression may also be a Boolean expression. In a while statement, the expression is evaluated prior to the execution of the loop. The loop is continually executed until the expression becomes zero or false. Following is the form of a while statement:
while (expression) statement;
The while statement is driven from within. The execution of the statement must affect the expression in such a way that it eventually reaches zero. At this point, the loop is terminated.
The do-while Statement
In the do statement, the expression is evaluated after the execution of the loop. The statement is executed first, then the expression is evaluated. The statement then repeats until the expression becomes zero or false. The do statement (or do-while statement) takes the following form:
do statement; while (expression);
Jump Statements and Labels
Jump statements transfer control without an associated condition. There are four statements that serve as jump statements: continue, break, return, and goto.
The continue Statement
The continue statement may only be used in an iteration statement. The continue statement allows control to pass to a continuation within the smallest enclosing within the loop (in other words, to the end of the loop).
The break Statement
The break statement can only occur in a switch statement or an iteration. It stops the statement or iteration within its smallest enclosing and passes control on to the statement following the terminated statement.
The return statement
The return statement is used to return from a function. It is categorized as a jump statement because it causes execution to return (jump back) to the point at which the call to the function was made.
The goto Statement
In general, you should avoid the use of the goto statement. However, situations can arise where using another control structure would be difficult or awkward. In such situations, a goto statement may be used. The goto statement transfers control to a labeled statement. The label must be identified within the current function -- the scope of a label is limited by the boundaries of the function in which it appears. Furthermore, goto statements should only be used when absolutely necessary, such as when you are dealing with an error that occurs within a process that will ultimately require the suspension of that process.