Lab 3: Experiment 2

Input Expressions

To make some of the other experiments easier, we'll take a look at input expressions.

Variables Only

Consider this statement:

cin >> 3;
What do you suppose this would mean? Maybe after this executes, every 3 the program encounters should be replaced with the value the user types in from the keyboard? That seems awfully silly and quite dangerous. So, a better question: does C++ even allow this? Try it. Add the input statement to your program and recompile.

Question #3.2.1: What is the first compiler error that you get?

Fortunately, C++ doesn't let us do something so silly.

Instead, all of the objects in an input expression must be variables. Let's try this:

cin >> i >> j;
Add this statement after the declaration of i and j, but before the output statement. When you run your program, enter these values:
123  456

Question #3.2.2: What values are printed for i and j? Did these values come from the declaration or from your keyboard input?

An input statement replaces the value in a variable used in the input statement. The variable does not remember its old values; the old value is gone.

Replacing Values

Try this variation:

Question #3.2.3: What happens if the input line is moved before the declaration?

That's actually a review of the previous lab. Remember that you can't use a variable unless you declare it first. The order of the statements matter.

Here's a variation that will compile and execute:

Question #3.2.4: What happens if the input line is moved after the output statement?

Question #3.2.5: Use the results of this experiment to justify the claim that an input statement replaces the values in its variables.

Question #3.2.6: Is it necessary to initialize i and j in their declaration if we read in values for them in the very next statement?

Wrapping Up

Move the input statement back between the declaration and output statements.

Back to the Lab Exercise  |  Forward to the Next Experiment
© 2003 by Prentice Hall. All rights reserved.
Report all errors to Jeremy D. Frens.