C++ Demystified(c) A Self-Teaching Guide
Assigning Values to Variables
The purpose of a variable is to store information. Therefore, after you have created a variable, the next logical step is to specify the information that the variable will store. This is called assigning a value to a variable.
A variable can be assigned a value supplied by the programmer in code. A variable also can be assigned a value by the user , usually via the keyboard, when the program is running.
You may use the assignment operator, which is discussed in the next section, to specify the value to be stored in a variable. You use the cin object (discussed in the upcoming section Using the cin Object) after the assignment operator, to obtain the user s input, usually from the keyboard, and then store that input in a variable.
Assignment Operator
You use the assignment operator to assign a value to a variable. The syntax is
[variable name] = [value];
The assignment operator looks like the equal sign. However, in C++ the = sign is not used to test for equality; it is used for assignment. As you will learn in Chapter 5, in C++ the equal sign is ==, also called the equality operator.
The variable must be declared either before, or at the same time, you assign it a value, not afterwards. In the following example, the first statement declares the variable, and the second statement assigns a value to that variable:
int testScore; testScore = 95;
The next example concerns initialization, which is when you assign a value to a variable as part of the same statement that declares that variable:
int testScore = 95;
However, the variable cannot be declared after you assign it a value. The following code will cause the compiler error undeclared identifier at the line testScore = 95:
testScore = 95; int testScore;
As mentioned earlier in the Declaring Variables section, this compiler error will occur even though the variable is declared in the very next line because the compiler reads the code from top to bottom, so when it reaches the line testScore = 95, it has not seen the variable declaration.
The value assigned need not be a literal value, such as 95. The following code assigns to one integer variable the value of another integer variable.
int a, b; a = 44; b = a;
The assignment takes place in two steps:
-
First, the value 44 is assigned to the variable a.
-
Second, the value of a, which now is 44, is assigned to the variable b.
You also can assign a value to several variables at once. The following code assigns 0 to three integer variables:
int a, b, c; a = b = c = 0;
The assignment takes place in three steps, from right to left:
-
The value 0 is assigned to the variable c.
-
The value of the variable c, which now is 0, is next assigned to the variable b .
-
The value of the variable b, which now is 0, is assigned to the variable a.
Finally, you can assign a value to a variable after it has already been assigned a value. The word variable means likely to change or vary. What may change or vary is the variable s value. The following code demonstrates a change in the value of a variable that was previously assigned a value:
#include <iostream> using namespace std; int main(void) { int testScore; testScore = 95; cout << "Your test score is " << testScore << "\n"; testScore = 75; cout << "Your test score now is " << testScore << "\n"; return 0; }
The output is
Your test score is 95 Your test score now is 75
Assigning a Compatible Data Type
The value assigned to a variable must be compatible with the data type of the variable that is the target of the assignment statement. Compatibility means, generally , that if the variable that is the target of the assignment statement has a numeric data type, then the value being assigned must also be a number.
The following code is an example of incompatibility . If it is placed in a program, it will cause a compiler error.
int testScore; testScore = "Jeff";
The description of the compiler error is cannot convert from ˜const char [5] to ˜int . This is the compiler s way of telling you that you are trying to assign a string to an integer, which of course won t work; Jeff cannot represent an integer.
The value being assigned need not necessarily be the exact same data type as the variable to which the value is being assigned. In the following code, a floating-point value, 77.83, is being assigned to an integer variable, testScore. The resulting output is The test score is 77.
#include <iostream> using namespace std; int main(void) { int testScore; testScore = 77.83; cout << "The test score is " << testScore << "\n"; return 0; }
While the code runs, data is lost, specifically the value to the right of the decimal point. .83. The fractional part of the number cannot be stored in testScore, that variable being a whole number.
Overflow and Underflow
You may recall from Chapter 2 that the short data type has a range from “32768 to 32767. You can run the following program to see what happens when you attempt to assign to a variable a value that is compatible (here a whole number for a short data type) but that is outside its range.
#include <iostream> using namespace std; int main(void) { short testScore; testScore = 32768; cout << "Your test score is " << testScore << "\n"; return 0; }
The output is Your test score is “32768. That s right, not 32768, but “32768.
This is an example of overflow. Overflow occurs when a variable is assigned a value too large for its range. The value assigned, 32768, is 1 too large for the short data type. Therefore, the value overflows and wraps around to the data type s lowest possible value, “32768.
Similarly, an attempt to assign to testScore 32769, which is 2 too large for the short data type, would result in an output of “32767, an attempt to assign to testScore 32770, which is 3 too large for the short data type, would result in an output of “32766, and so on. Figure 3-2 illustrates how the overflow value is reached.
The converse of overflow is underflow. Underflow occurs when a variable is assigned a value too small for its range. The output of the following code is Your test score is 32767. The value assigned, “32769, is 1 too small for the short data type. Therefore, the value underflows and wraps around to the data type s highest possible value, 32767.
#include <iostream> using namespace std; int main(void) { short testScore; testScore = -32769; cout << "Your test score is " << testScore << "\n"; return 0; }
Similarly, an attempt to assign to testScore “32770, which is 2 too small for the short data type, would result in an output of 32766, an attempt to assign to testScore “32771, which is 3 too small for the short data type, would result in an output of 32765, and so on. Figure 3-3 illustrates how the underflow value is reached.
Note | Floating-point variables, of the float or double data type, also may overflow or underflow. However, the result depends on the compiler used, and may be a run-time error stopping your program, or instead an incorrect result. |
Using the cin Object
Thus far, the programmer has supplied the values that are assigned to variables. However, most programs are interactive, asking the user to provide information, which the user then inputs, usually via the keyboard.
In Chapter 1, we used the cout object to output information to a standard output, usually the monitor. Now we will use the cin object to obtain information from standard input, which usually is the keyboard. The cin object, like the cout object, is defined in the standard library file <iostream>, which therefore must be included (with an include directive) if your code uses cin.
The syntax of a cin statement is
cin >> [variable name];
The cin object is followed by >>, which is the stream extraction operator. It obtains the input, usually from the keyboard, and assigns that input to the variable to its right.
Tip | Knowing when to use >> instead of << can be confusing. It may be helpful to remember that the >> and << operators each point in the direction that data is moving. For example in the expression cin >> var, data is moving from standard input into the variable var . By contrast, in the expression cout >> var, the << indicates that data is moving from the variable var to standard output. |
When your program reaches a cin statement, its execution halts until the user types something at the keyboard and presses the ENTER key. Try running the following program. You will see a blinking cursor until you type a number. Once you type a number and press ENTER , the program will output Your test score is followed by the number you inputted. For example, if you inputted 100, the output will be Your test score is 100.
#include <iostream> using namespace std; int main(void) { int testScore; cin >> testScore; cout << "Your test score is " << testScore << "\n"; return 0; }
This program is not very user friendly. Unless the user happened to know what your program did, they would not know what information is being asked of them. Accordingly, a cin statement usually is preceded by a cout statement telling the user what to do. This is called a prompt. The following code adds a prompt:
#include <iostream> using namespace std; int main(void) { int testScore; cout << "Enter your test score: "; cin >> testScore; cout << "Your test score is " << testScore << "\n"; return 0; }
The program input and output could be
Enter your test score: 78 Your test score is 78
Assigning a Compatible Data Type
As with the assignment operator, the value being assigned by the cin operator need not necessarily be the exact same data type as that of the variable to which the value is being assigned. In the previous program, entering a floating-point value, 77.83, at the prompt for entry of the test score results in the following output: The test score is 77. Data is lost, though, specifically the part of the number to the right of the decimal point. The cin statement will not read the part of the number to the right of the decimal point because it cannot be stored in a whole number variable.
However, the value being assigned by the cin operator must be compatible with the data type of the variable to which the value is being assigned. In the preceding program, typing Jeff at the prompt for entry of the test score results in the following output: Your test score is “858993460.
Obviously, “858993460 is not a test score anyone would want. Less obvious is the reason why that number is outputted.
The string literal Jeff cannot be assigned to an integer variable such as testScore. Therefore, the cin operator will not assign Jeff to that integer variable. Therefore, when the cout statement attempts to output the value of testScore, that variable has not yet been assigned a value.
When testScore was declared, there was some value at its memory address left over from programs previously run on the computer. The cout statement, when trying to output the value of testScore, does the best it can and attempts to interpret this leftover value. The result of that interpretation is “858993460.
Note | Compile Time vs. Run-Time Difference When Incompatible Data Types Are Assigned ”Earlier in this chapter, the attempt to assign Jeff to testScore ( testScore = Jeff ;) resulted in a compiler error. Here, the attempt to assign Jeff to testScore using a cin statement instead results in an incorrect value. The reason that this time there is no compiler error is because the value the user would input could not be known at compile time, but instead would be known only at run time. Therefore, there would be no compile error, since at the time of compilation there was no attempt to assign an incompatible value. |
Inputting Values for Multiple Variables
If you are inputting values for several variables, you could input them one line at a time.
#include <iostream> using namespace std; int main(void) { int myWeight, myHeight; string myName; cout << "Enter your name: "; cin >> myName; cout << "Enter your weight in pounds: "; cin >> myWeight; cout << "Enter your height in inches: "; cin >> myHeight; cout << "Your name score is " << myName << "\n"; cout << "Your weight in pounds is " << myWeight << "\n"; cout << "Your height in inches is " << myHeight << "\n"; return 0; }
The output of the program, with the input of Jeff for the name, 200 for the pounds, and 72 for the height, is
Enter your name: Jeff Enter your weight in pounds: 200 Enter your height in inches: 72 Your name is Jeff Your weight in pounds is 200 Your height in inches is 72
Instead of having separate prompts and cin statements for each variable, you can have one cin statement assign values to all three variables. The syntax is
cin >> [first variable] >> [second variable] >> [third variable];
The same syntax would work when using one cin statement to assign values to four or more variables. The variables are separated by the stream extraction operator >>.
When you use one cin statement to assign values to multiple variables, the user separates each input by one or more spaces. The space tells the cin object that you have finished assigning a value to one variable and the next input should be assigned to the next variable in the cin statement. As before, the user finishes input by choosing the ENTER key.
The following program uses one cin statement to assign values to three variables:
#include <iostream> using namespace std; #include <string> int main(void) { int myWeight, myHeight; string name; cout << "Enter your name, weight in pounds and height in inches\n"; cout << "The three inputs should be separated by a space\n"; cin >> name >> myWeight >> myHeight; cout << "Your name is " << name << "\n"; cout << "Your weight in pounds is " << myWeight << "\n"; cout << "Your height in inches is " << myHeight << "\n"; return 0; }
The interaction between user input and the cin statement could be as follows :
-
The user would type Jeff, followed by a space.
-
The space tells the cin object that the first input has ended, so the cin object will assign Jeff to the first variable in the cin statement, name.
-
The user would type 200, followed by a space.
-
The space tells the cin object the second input has ended, so the cin object will assign 200 to the next variable in the cin statement, myWeight.
-
The user would type 200, and then press the ENTER key.
-
The ENTER key tells the cin object that the third and final input has ended, so the cin object will assign 72 to the remaining variable in the cin statement, myHeight, which completes execution of the cin statement.
The resulting program output would be
Enter your name, weight in pounds and height in inches The three inputs should be separated by a space Jeff 200 72 Your name is Jeff Your weight in pounds is 200 Your height in inches is 72
Assigning a Compatible Data Type
The data types in the cin statement may be different. In this example, the data type of the first variable is a string, whereas the data type of the second and third variables is an integer.
What is important is that the order of the input matches the order of the data types of the variables in the cin statement. The input order Jeff, 200, and 72 is assigned to the variables in the order of their appearance in the cin statement, myName, myWeight, and myHeight. Therefore, Jeff is assigned to the string variable myName, 72 to the integer variable myWeight, and 200 to the integer variable myHeight.
The importance of the order of the input matching the order of the data types of the variables in the cin statement is demonstrated by changing the order of the user s input from Jeff, 200, and 72, to 200, Jeff, and 72. The program output then would be
Enter your name, weight in pounds and height in inches The three inputs should be separated by a space 200 Jeff 72 Your name is 200 Your weight in pounds is -858993460 Your height in inches is -858993460
While I would like to lose weight, “858993460 seems a bit extreme. Also, while it is understandable why Jeff cannot be assigned to my weight, 72 was not assigned to my height either.
The one output that is correct is the name. Any characters , including digits, can be part of a string. Therefore, while 200 may be an unusual name to us, it is perfectly OK for cin, which therefore assigns 200 to the string variable name.
Why “858993460 was outputted for myWeight also has been explained earlier in the example in which the user entered Jeff at the prompt to enter a test score.
However, 72 would be a valid value for assignment to the integer variable myHeight. Why then isn t 72 the output for height?
The reason is that the next value for cin to assign is not 72, but instead Jeff. Since cin was unable to assign Jeff to myWeight, the value Jeff remains next in line for assignment, this time to the variable myHeight. Unfortunately, cin is unable to assign Jeff to myHeight either, so the value of myHeight, like myWeight, also is outputted as “858993460.
Inputting Multiple Words into a String
Finally, cin will only take the first word of a string. If in the following program you input Jeff Kent at the prompt, the output will be Your name is Jeff not Your name is Jeff Kent.
#include <iostream> using namespace std; #include <string> int main(void) { string name; cout << "Enter your name: "; cin >> name; cout << "Your name is " << name; return 0; }
The reason why the value of name is outputted only as Jeff, omitting Kent, is that the cin object interprets the space between Jeff and Kent as indicating that the user has finished inputting the value of the name variable.
The solution involves using either the get or getline method of the cin object. These methods will be covered in Chapter 10.
Overflow and Underflow
The consequences of an overflow or underflow of whole number variables is more unpredictable with cin than with the assignment operator. Inputting either 32768, which is 1 more than the highest number in the range of a short data type, or “32769, 1 less than the lowest number in that range, results on my computer in the output Your test score is “13108.
#include <iostream> using namespace std; int main(void) { short testScore; testScore = 32768; cout << "Your test score is " << testScore << "\n"; return 0; }
Категории