Chapter 4
IN THIS CHAPTER
Using storage bins called variables
Working with integer and character variables
Manipulating strings
Using Boolean variables and conditional operators
Reading from the console
Everyone loves to store things away. The closet is a perfect example of a place to store things. You may have boxes in your closets that you haven’t opened in years. Perhaps you inadvertently created a time capsule. Or just a fire hazard. When you program a computer, you can also store things away. Most people know that a computer has two kinds of memory: memory inside a chip and memory on a hard drive. But most people use the term memory in reference to chip memory; the other is referred to as simply the hard drive. When you type a business letter in a word processor, the letter is stored in memory. After you choose File ⇒ Save, the letter gets stored on the hard drive, but as long as you still have the letter open in the word processor, it’s generally still in memory.
The best way to think of memory is as a set of storage bins, much like the ones in the closets that you’re afraid of. When you write a computer application, you reserve some storage bins, and you give each storage bin a name. You also say what type of thing can be stored in the storage bin. The technical term for such a storage bin is a variable.
In this chapter, you discover how you can use these storage bins in your applications.
When you write an application, you specify that you want to make use of one or more storage bins called variables. You can put different kinds of things in these storage bins. The difference between these computer storage bins and those in your closet, however, is that each computer storage bin can hold only one thing at a time.
You can put many different types of things into your variables, too. For example, you can put numbers in a storage bin, or you can put a string in a storage bin. (However, each storage bin contains a unique kind of data — you can’t put a number into a storage bin designed for a string.) Book 1, Chapter 3 advises that a string is simply a bunch of letters, digits, punctuation marks, or other characters all strung together. As for numbers, they can be either integers (which are positive whole numbers, negative whole numbers, and 0) or numbers with a decimal point, such as 3.11 or 10.0, which (for various reasons) are called floating-point numbers.
In your C++ application, you can easily write a line of code that creates a variable. Although what you’re doing at that point is simply writing code (and the variable doesn’t actually get created until you run the application), people often refer to this process as creating a variable. A variable has three aspects, as shown in Table 4-1.
TABLE 4-1 A Variable Has Three Aspects
Aspect |
What It Means |
---|---|
Name |
The name you use in your application to refer to the variable |
Type |
The type of information that the variable can hold |
Value |
The actual thing that the storage bin holds |
The following list describes the items in Table 4-1 in more detail.
count
, and you may have a variable called LastName
. Or you could have a variable called MisterGates
.10
, and a character variable might hold the character a
. In your application, you can store something in a variable, and later you can store something else in the variable. When you store something else, the variable forgets what was previously inside it. So, in this sense, you can think of a computer as having a one-track mind.The code for the SimpleVariable
example, shown in Listing 4-1, demonstrates how to create a variable. This is a full application that you can run.
LISTING 4-1: Creating a Variable
#include <iostream>
using namespace std;
int main()
{
int mynumber;
mynumber = 10;
cout << mynumber << endl;
return 0;
}
Take a careful look at Listing 4-1. Remember that the computer starts with the code inside the braces that follow the word main
, and it performs the code line by line.
The first line inside main
looks like this:
int mynumber;
When you declare a variable, the first thing you specify is the type of thing the variable can hold. Here, you use the word int
. This word is the C++ word for integer. Thus, the variable that you’re declaring can hold an integer. Next is the name of the variable. This variable is named mynumber
. Then a semicolon ends the variable declaration.
Notice that, in this line, you’ve covered two of the three aspects of variables: You have given the variable a name, and you have told the computer what type of thing you want the variable to hold. The order seems a little odd — in C++, you first say the type and then the name. That’s just the way it’s done in C++, and a good reason stands behind it, which you can read about in “Declaring multiple variables,” later in this chapter.
The next line looks like this:
mynumber = 10;
This line puts something in the variable. It puts the number 10
in it. Because you already know that the variable can hold an integer, you’re allowed to put in a 10
because it is an integer. If you had tried to put something other than an integer in the variable, the compiler would have given you an error. The compiler makes sure that you put into a variable only the type of thing that you said you would. The compiler is good at keeping you in line. And of course you noticed that the statement ends with a semicolon. In C++, every statement ends with a semicolon.
cout << mynumber << endl;
Book 1, Chapter 3 describes what this line does. It’s a cout
statement, which means that it writes something on the console. As you can probably guess, this code tells the computer to write the value of mynumber
on the console. It does not write the string mynumber
. Rather, it writes whatever happens to be stored in the storage bin. The previous line of code puts a 10
in the storage bin, and so this line prints a 10
on the console. When you run the application, you see this:
10
Many years ago, when the original C programming language first appeared (which was the language that served as the predecessor to C++), many developers thought it odd that they had to first say the type of the variable and then the name. But this actually works out well because it makes declaring multiple variables of the same type easy. If you want to declare three integer variables in a row, you can do it all in one shot, like this:
int tom, dick, harry;
This statement declares three separate variables. The first is called tom
; the second is called dick
; and the third is called harry
. Each of these three variables holds an integer. You have not put anything in any of them, so you may follow that with some code to stuff each of them full with a number. For example, this code puts the number 10
in tom
, the number 20
in dick
, and the number 3254
in harry
.
tom = 10;
dick = 20;
harry = 3254;
Although a variable can hold only one thing at a time, you can still change what the variable holds. After you put something else in a variable, it forgets what it originally had. So when people accuse you of being forgetful, you can just say, “Yes, but you should see that computer I work with all day long!”
You put something new in the variable in the same way you originally put something in it. Look closely at the code for the ChangeVariable
example in Listing 4-2. Notice that the first part of the application is just like Listing 4-1. But then you add two more lines (shown in bold) that look pretty much like the previous two: The first one sticks 20
in the same variable as before, and the next one writes this new value out to the console.
LISTING 4-2: Changing a Variable
#include <iostream>
using namespace std;
int main()
{
int mynumber;
mynumber = 10;
cout << mynumber << endl;
mynumber = 20;
cout << mynumber << endl;
return 0;
}
As before, the line where you put something new in the variable follows the same format: There’s an equals sign, with the variable on the left and the new value on the right. As described earlier in this chapter, this statement is an assignment statement.
Because you can do only two direct things with variables — put something in and retrieve the value — setting one variable equal to another is a simple process of retrieving the value of one variable and putting it in the other. This process is often referred to as copying the variable from one to another. For example, if you have two integer variables — say, start
and finish
— and you want to copy the value of start
into finish
, you would use a line of code like the following:
finish = start;
After the computer runs this copy statement, the two variables hold the same thing. The code for CopyVariable
, shown in Listing 4-3, is an example of copying one variable to another.
LISTING 4-3: Copying a Value from One Variable to Another
#include <iostream>
using namespace std;
int main()
{
int start = 50;
int finish;
finish = start;
cout << finish << endl;
return 0;
}
When you create a variable, it starts as an empty storage bin. Before it can be of much use, you need to put something in it.
You can initialize a variable in two ways. The first way is by declaring the variable and then assigning something into it, which takes two lines of code:
int mynumber;
mynumber = 153;
But the other way is a bit quicker. It looks like this:
int mynumber = 153;
This method combines both strategies into one neat little package that is available for you to use whenever you want. You see variables initialized both ways in this book, depending what is clearer or more convenient at the time.
Every variable needs to have a name. But what names can you use? Although you are free to use names such as Fred
, Zanzibar
, or Supercount1000M
, there are limits to what C++ will allow you to use.
Here are the rules you need to follow when creating a variable name:
Examples of acceptable variable names are Count
, current_name
, address_1000
, and LookupAmount
. Some variable names are legal, but not easily understood, such as _
, __
, and _12
— none of which tell you what the variable contains. Table 4-2 lists some variable names that are not allowed.
TABLE 4-2 Examples of Bad Variable Names
Bad Variable Name |
Why It’s Not Allowed |
---|---|
12345 |
It has only numbers (and it starts with a number, which is wrong as well). |
A&B |
The only special character allowed is the underscore, _. The ampersand (&) is not allowed. |
1abc |
A variable name cannot start with a number. |
A potter who is creating an elegant vase is said to manipulate the clay. Likewise, you can manipulate variables to create a thing of abstract beauty. But in this case, manipulation means simply that you can do arithmetic. You can easily do the usual addition, subtraction, multiplication, and division. Book 1, Chapter 3, introduces the characters that you use for the arithmetic operations. They are:
You can, however, perform another operation with integers, and it has to do with remainders and division. The idea is that if you divide, for example, 16 by 3, the answer in whole numbers is 5 remainder 1. Another way of saying this is that 16 doesn’t divide by 3 evenly, but 3 “goes into” 16 five times, leaving a remainder of 1. This remainder is sometimes called a modulus. Computer people actually have an important reason for calling it modulus rather than remainder, and that’s because people in the computer field like to use confusing terms.
If you want to add two integer variables, use the + symbol. You can either print the result or put it back into a variable.
The AddInteger
example adds two variables (start
and time
) and then prints the answer to the console. The addition operation is shown in bold.
#include <iostream>
using namespace std;
int main()
{
int start;
int time;
start = 37;
time = 22;
cout << start + time << endl;
return 0;
}
In this example, however, the computer doesn’t actually do anything with the final sum, 59
, except print it. If you want to use this value later, you can save it in its own variable. The AddInteger2
example demonstrates how to save the result in a variable; the storage operation is shown in bold:
#include <iostream>
using namespace std;
int main()
{
int start;
int time;
int total;
start = 37;
time = 22;
total = start + time;
cout << total << endl;
return 0;
}
In this code, you declare the integer variable total
along with the others. Then after you store 37
in start
and 22
in time
, you add the two and save the total in the variable called total
. Then you finally print the value stored in total
.
You can also add numbers themselves to variables. The following line adds 5 to start
and prints the result:
cout << start + 5 << endl;
Or you can save the value back in another variable, as in the following fragment:
total = start + 5;
cout << total << endl;
This example adds 5
to start
and saves the new value in total
.
Here’s where things get a little tricky in the logical arena. This might seem strange at first, but you can actually do something like this:
total = total + 5;
If you have taken some math courses, you might find this statement a little bizarre, just like the math courses themselves. But remember that total
is a variable in computer programming, and that definition is a bit different from the math world.
This statement really just means you’re going to add 5
to the value stored in total
, and you’ll take the value you get back and store it back in total. In other words, total
will now be 5
greater than it was to begin with. The AddInteger3
example shows this technique in action:
#include <iostream>
using namespace std;
int main()
{
int total;
total = 12;
cout << total << endl;
total = total + 5;
cout << total << endl;
return 0;
}
When you run this application, you see the following output on the console:
12
17
Notice what took place. First, you put the value 12
inside total
and print the value to the console. Then you add 5
to total
, store the result back in total
, and print the new value of total
to the console.
Now, it’s no big secret that we computer people are lazy. After all, why would we own computers if we weren’t? And so the great makers of the C++ language gave us a bit of a shortcut for adding a value to a variable and storing it back in the variable. The line
total = total + 5;
is the same as
total += 5;
We computer folks also have a special way of pronouncing +=. We say “plus equal.” So for this line, we would say, “Total plus equal five.”
You can also use the +=
notation with other variables. For example, if you want to add the value in time
to the value in total
and store the result back in total
, you can do this
total = total + time;
or you can use this shortcut:
total += time;
If you are adding just 1 to a variable, which is called incrementing the variable, you can use an even shorter shortcut. It looks like this:
total++;
This is the same as total = total + 1;
or total += 1;
.
Table 4-3 summarizes the different things you can do that involve the addition of variables. Note that when you see ++
, which is the increment operator, it’s pronounced plus plus, not double plus.
TABLE 4-3 Doing Things with Addition
What You Can Do |
Sample Statement |
---|---|
Add two variables |
|
Add a variable and a number |
|
Add two variables and save the result in a variable |
|
Add a variable and a number and save the result in a variable |
|
Add a number to what’s already in a variable |
|
Add a number to what’s already in a variable by using a shortcut |
|
Add a variable to what’s already in a variable |
|
Add a variable to what’s already in a variable by using a shortcut |
|
Add 1 to a variable |
|
Everything you can do involving the addition of integer variables you can also do with subtraction. For example, you can subtract two variables, as shown in the SubtractVariable
example in Listing 4-4.
LISTING 4-4: Subtracting Two Variables
#include <iostream>
using namespace std;
int main()
{
int final;
int time;
final = 28;
time = 18;
cout << final - time << endl;
return 0;
}
When this application runs, the console shows the number 10
, which is 28 – 18
. Remember that, as with addition, the value of neither final
nor time
actually change. The computer just figures out the difference and prints the answer on the console without modifying either variable.
You can also subtract a number from a variable, and (as before) you still aren’t changing the value of the variable, as in the following example:
cout << final - 5 << endl;
You can subtract one variable from another and save the result in a third variable:
start = final - time;
And you can change the value in a variable by using subtraction, as in the following four sample lines of code. This first subtracts time
from final
and saves the result back in final
:
final = final - time;
Or you can do the same thing by using the shortcut notation:
final -= time;
Or you can do the same thing with a number:
final = final - 12;
And (as before) you can alternatively do the same thing with a shortcut:
final -= 12;
Finally, as with addition, you have a shortcut to a shortcut. If you want only to subtract 1, you can simply use two minus signs, as in
Final— —;
This line is pronounced minus minus. The --
is the decrement operator and when applied to a variable is called decrementing the variable.
To do multiplication in C++, you use the asterisk (*) symbol. As with addition and subtraction, you can multiply two variables, or you can multiply a variable by a number. You can either print the result or save it in a variable. For example, you can multiply two variables and print the results to the console with the following line:
cout << length * width << endl;
Or you can multiply a variable by a number, as in this line:
cout << length * 5 << endl;
And as with addition and subtraction, you can multiply two variables and save the result in a third variable:
area = length * width;
Also, you can use multiplication to modify a variable’s value, as in
total = total * multiplier;
Or, to use the shortcut:
total *= multiplier;
And (as before) you can do the same with just a number:
total = total * 25;
or this:
total *= 25;
Although addition, subtraction, and multiplication are straightforward with integer variables, division is a bit trickier. The chief reason is that, with whole numbers, sometimes you just can’t divide evenly. It’s like trying to divide 21 tortilla chips evenly among five people. You just can’t do it. Either somebody will feel cheated, or everyone will get four chips, and one will be left over for everyone to fight over. Of course, you could break every chip into five pieces, and then each person gets ⅕ of each chip, but then you’re no longer working with whole numbers — just a bunch of crumbs.
If you use a calculator and type 21 divided by 5, you get 4.2, which is not a whole number. If you want to stick to whole numbers, you have to use the notion of a remainder. In the case of 21 divided by 5, the remainder is 1, as you figured out with the tortilla chips. The reason is that the highest multiple of 5 in 21 is 20 (because 5 times 4 is 20), and 1 is left over. That lonely 1 is the remainder.
So in terms of strictly whole numbers, the answer to 21 divided by 5 is 4 remainder 1. And that’s how the computer does arithmetic with integers: It gets two different answers: The quotient and the remainder. In math terms, the main answer (in the example, 4) is the quotient. What’s left over is the remainder.
Because two different answers to a division problem may occur, C++ uses two different operators for figuring these two different answers.
To find the quotient, use the slash (/). Think of this character as the usual division operator, because when you deal with numbers that divide evenly, this operator gives you the correct answer. Thus, 10 / 2 gives you 5, as you would expect. Further, most people just call this the division operator, anyway.
To find the remainder, use the percent sign (%). This is often called the modulus operator.
The DivideInteger
example, shown in Listing 4-5, takes two numbers and prints their quotient and remainder. Then it does it again for another pair of numbers. The first pair has no remainder, but the second pair does.
LISTING 4-5: Finding Quotients and Remainders
#include <iostream>
using namespace std;
int main()
{
int first, second;
cout << "Dividing 28 by 14." << endl;
first = 28;
second = 14;
cout << "Quotient " << first / second << endl;
cout << "Remainder " << first % second << endl;
cout << "Dividing 32 by 6." << endl;
first = 32;
second = 6;
cout << "Quotient " << first / second << endl;
cout << "Remainder " << first % second << endl;
return 0;
}
When you run this application, you see the following output:
Dividing 28 by 14.
2
0
Dividing 32 by 6.
5
2
You have access to all the usual goodies with both the division (/
) and modulus (%
) operators. For example, you can store the quotient in another variable, as you can with the remainder:
myQuotient = first / second;
myRemainder = first % second;
And you have shortcuts available:
int first = 30;
first /= 5;
cout << first << endl;
In this case, the value of first
becomes 6
because 30 / 5
is 6
. And in the following case, the value of first
becomes 3
because the remainder of 33
divided by 6
is 3
:
int first = 33;
first %= 5;
cout << first << endl;
Another type of variable you can have is a character variable. A character variable can hold a single — just one — character that C++ stores as a number. It holds a value between –127 and 128 (char
or signed char
) or between 0 and 255 (unsigned char
). Normally, a character is anything that can be typed, such as a letter of the alphabet, a digit, or another symbol you see on the computer keyboard, but a character can also hold nonprintable values found in an ASCII table (see https://en.cppreference.com/w/cpp/language/ascii
). Some of these unprintable characters are control characters (so called because they control the appearance of text on the screen), such as the tab, carriage return, and newline character.
To use a character variable, you use the type name char
. To initialize a character variable, you put the character inside single quotes. (If you use double quotes, the compiler issues an error message because double quotes create a string, which can contain multiple characters rather than a single character.) The following is an example of a character:
char ch;
ch = 'a';
cout << ch << endl;
The character variable here is called ch
, which is initialized to the character a
. It’s surrounded by single quotes. The code then prints it by using cout
.
One important character in the programming world is the null character. Deep down inside the computer’s memory, the computer stores each character by using a number, and the null character’s number is 0. There’s nothing to actually see with the null character; this book can’t contain a picture of it for you to hang on your wall. (Bummer.) The book can only describe it. Yes, every once in a while, computer people have to become philosophers. But the null character is important because it is often used to signify the end of something — not the end of the world or anything big like that, but the end of some data.
To notate the null character in C++, use \0
, as in
char mychar = '\0';
In addition to the null character, several other cool characters are available — some that have a look to them and can be printed and some that do not and cannot. The null character is an example of a nonprintable character. You can try to print one, but you get either a blank space or nothing at all, depending on the compiler.
But some characters are special in that they do something when you print, though you can’t type them directly. One example is the newline character. The newline character (\n
) symbolizes the start of a new line of text. In all cases, the computer places the insertion point, the place where it adds new characters, on the next line. If you are printing some text to the console and then you print a newline character, any text that follows will be on the next line. Most compilers these days start the text at the far left end of the next line (Column 1), but some compilers start the text in the next column on the next line, as in the following output. In this case, the text appears on the next line, but it starts at Column 4 rather than at the far left end (Column 1):
abc
def
Here, you print abc
, and then a newline, and then def
. Notice that the def
continues in the same position it would have been had it been on the first line. For the compilers used in this book, however, printing abc
, and then a newline, and finally def
results in this output:
abc
def
But to accommodate the fact that some other compilers sometimes treat a newline as just that (start a new line but don’t go anywhere else), the creators of the computers gave you another special character: the carriage return. (Can you hear the crowd say, “Ooooh!”?)
The carriage return character (\r
) places the insertion point at the start of the line, but not on a new line (which means that if you use just a carriage return on a computer expecting both a carriage return and a newline, you overwrite what’s already on the line). That’s true with pretty much every C++ compiler.
The “Tabbing your output” section of Book 1, Chapter 3, describes the tab character (\t
) and other characters that start with a backslash. These are individual characters, and you can have them inside a character variable, as in the following example, which prints the letter a, and then a tab, and then the letter b. Notice that, to get the tab character to go into the character variable, you have to use the \
and then a t
:
char ch = '\t';
cout << "a" << ch << "b" << endl;
Book 1, Chapter 3 mentions that to put a double quote inside a string, you need to precede the double quote with a backslash so that the computer won’t think that the double quote is the end of the string. But because a character is surrounded by single quotes, you don’t need to do this. You can just put a double quote inside the character, as in
char ch = '"';
Of course, that raises an important question now: What about single quotes? This time, you do have to use the backslash:
char ch = '\'';
And finally, to put a backslash inside a character, you use two backslashes:
char ch = '\\';
If any single computer word has become so common in programming that most computer people forget that it’s a computer word, it’s string. Book 1, Chapter 3 introduces strings and describes what they are, and it gives examples of them. In short, a string is simply a set of characters strung together. The compiler knows the start and end of a string in your code based on the location of the double quotes.
You can create a variable that can hold a string. The type you use is string
. The CreateString
example, shown in Listing 4-6, demonstrates how to use a string
variable.
LISTING 4-6: Using Brackets to Access Individual Characters in a String
#include <iostream>
using namespace std;
int main()
{
string mystring;
mystring = "Hello there";
cout << mystring << endl;
return 0;
}
When you run this application, the string Hello there
appears on the console. The first line inside main()
creates a string variable called mystring
. The second line initializes it to "Hello there"
. The third line prints the string to the console.
Accessing the individual characters within a string is easy. Take a look at the IndividualCharacter
example shown in Listing 4-7.
LISTING 4-7: Using the string Type to Create a String Variable
#include <iostream>
using namespace std;
int main()
{
string mystring;
mystring = "abcdef";
cout << mystring[2] << endl;
return 0;
}
Notice that the ninth line, the cout
line, has the word mystring
followed by a 2
inside brackets ([]
). When you run this application, here’s what you see:
c
That’s it, just a letter c
, hanging out all by itself. The 2
inside brackets means that you want to take the second character of the string and only that character. But wait! Is c
the second character? Your eyes may deceive you, but it looks like that’s the third character. What gives?
A string is made of characters. Thus, a single character within a string has the type char
. This means that you can do something like this (as shown in the IndividualCharacter2
example):
#include <iostream>
using namespace std;
int main()
{
string mystring;
mystring = "abcdef";
char mychar = mystring[2];
cout << mychar << endl;
}
In this example, mychar
is a variable of type char
. The mystring[2]
expression returns an item of type char
. Thus, the assignment is valid. When you run this, you once again see the single character in the third position:
c
Using the bracket notation, you can also change a character inside a string. The following code, for example, changes the second character in the string (that is, the one with index
) from a 1
b
to a q
:
string x = "abcdef";
x[1] = 'q';
cout << x << endl;
This code writes the string aqcdef
to the console.
Any good writer can keep adding more and more letters to a page. And the same is true with the string
type: You can easily add to it. The following lines of code use the +=
operator, which was also used in adding numbers. What do you think this code will do?
string mystring;
mystring = "Hi ";
mystring += "there";
cout << mystring << endl;
The first line declares the string mystring
. The second line initializes it to "Hi "
. But what does the third line do? The third line uses the +=
operator, which appends something to the string — in this case, "there"
. Thus, after this line runs, the string called mystring
contains the string "Hi there"
, and that’s what appears on the console when the cout
line runs. The fancy programmer term for adding something to a string is concatenation.
You can also do something similar with characters. The following code snippet adds a single character to a string:
string mystring;
mystring = "abcdef";
mystring += 'g';
cout << mystring << endl;
This code creates a string with "abcdef"
and then adds a ’g’
character to the end to get "abcdefg"
. Then it writes the full "abcdefg"
to the console.
You can take two strings and add them together by using a +
sign, just as you can do with integers. The final result is a string that is simply the two strings pushed together, side by side. For example, the following code adds first
to second
to get a string called third
:
string first = "hello ";
string second = "there";
string third = first + second;
cout << third << endl;
This code prints the value of third
, which is simply the two strings pushed together — in other words, "hello there"
. (Notice that the string called first
has a space at its end, which is inside quotes and, therefore, part of the string.) You can also add a string constant (that is, an actual string in your application surrounded by quotes) to an existing string variable, as shown here:
string first = "hello ";
string third = first + "there";
cout << third << endl;
string bigstring = "hello " + "there";
cout << bigstring << endl;
Unfortunately, this won’t work. The reason is that (deep down inside its heart) the compiler just wants to believe that a string constant and a string are fundamentally different. But really, you don’t have a good reason to do this, because you can accomplish the same thing with this code:
string bigstring = "hello there";
cout << bigstring << endl;
One of the most important features of computers, besides allowing you to surf the web and allowing telemarketers to dial your telephone automatically while you’re eating, is the capability to make comparisons. Although this topic may not seem like a big deal, computer technology did not start to take off until the engineers realized that computers could become much more powerful if they could test a situation and do one task or another task, depending on the situation.
You can use many ways to write a C++ application that can make decisions; see Book 1, Chapter 5, for a discussion about this topic. But one way that is quite handy is the use of the conditional operator.
Think about this process: If two integer variables are equal, set a string variable to the string "equal"
. Otherwise, set it to the string "not equal"
. In other words, suppose that you have two integer
variables, called first
and second
. first
has the value 10
in it, and second
has the value 20
in it. You also have a string
variable called result
. Now, to follow the little process just described: Are the two variables equal? No, they are not, so you set result
to the string "not equal"
.
Now do this in C++. Look carefully at the following code. First, you declare the variables first
, second
, and result
:
int first = 10;
int second = 20;
string result;
So far, so good. Notice that you didn’t yet initialize the string variable result
. But now you’re going to write a single line of code that performs the process just described. First, look over the following example, and see whether you can figure out what it’s doing. Look carefully at the variables and what they may do, based on the process described earlier. Then the text explains what the code does.
result = (first == second) ? "equal" : "not equal";
The preceding line is probably one of the more bizarre-looking lines of C++ code that you’ll see in this book. First, you discover what it means. Then you break it into parts to understand why it means what it does.
In English, this means result
gets "equal"
if first
is equal to second
; otherwise, it gets "not equal"
.
Now break it into two parts. A single equals sign indicates that the left side, result
, receives what is on the right side. So you need to figure out that crazy business on the right side:
(first == second) ? "equal" : "not equal"
When you see this strange setup, consider the question mark to be the divider. The stuff on the left of the question mark is usually put in parentheses, as shown in the following:
(first == second)
This line actually compares first
to second
and determines whether they are equal. Yes, the code shows two equals signs. In C++, that’s how you test whether two things are equal. Now move to the part on the right of the question mark:
"equal" : "not equal"
This is, itself, two pieces divided by a colon, so if first
is indeed equal to second
, result
gets the string "equal"
. Otherwise, it gets the string "not equal"
. Take a look at the whole thing one more time:
result = (first == second) ? "equal" : "not equal";
Once again, consider what it means: If first
is equal to second
, result
gets "equal"
; otherwise, it gets "not equal"
.
Remember that the storage bin on the left side of the single equals sign receives what is on the right side. The right side is an expression, which comes out to be a string of either "equal"
or "not equal"
. The whole EqualityCheck
example is shown in Listing 4-8.
LISTING 4-8: Using the Conditional Operator to Do Comparisons
#include <iostream>
using namespace std;
int main()
{
int first = 10;
int second = 20;
string result;
result = first == second ? "equal" : "not equal";
cout << result << endl;
return 0;
}
In addition to integers and strings, another type in C++ can be pretty useful. This type is called a Boolean variable. Whereas an integer variable is a storage bin that can hold any integer value, a Boolean variable can hold only one of two different values: a true
or a false
. Boolean values take their name from George Boole, the father of Boolean logic. You can read about him at: http://mathshistory.st-andrews.ac.uk/Biographies/Boole.html
.
The type name for a Boolean variable is bool
. Therefore, to declare a Boolean variable, you use a statement like this:
bool finished;
This line declares a Boolean variable called finished
. Then you can put either a true
or a false
in this variable, as in the following:
finished = true;
or
finished = false;
When you print the value of a Boolean variable by using code like this:
cout << finished << endl;
you see either a 1
for true
or a 0
for false
. The reason is that, deep down inside, the computer stores a 1
to represent true
and a 0
to represent false
.
Throughout this chapter and the preceding chapter, you see many examples of how to write information to the console. But just writing information is sort of like holding a conversation where one person does all the talking and no listening. Getting some feedback from the users of your applications would be nice. Fortunately, getting feedback is easy in C++.Writing to the console involves the use of cout
in a form like this:
cout << "hi there" << endl;
Reading from the console (that is, getting a response from the user of your application) uses the cin
object. (It’s pronounced “see-in”.) Next, instead of using the goofy-looking <<
operator, you use the equally but backwardly goofy >>
operator.
The ReadString
example, shown in Listing 4-9, demonstrates how you can read a string from the console.
LISTING 4-9: Using the Conditional Operator to Make Comparisons
#include <iostream>
using namespace std;
int main()
{
string name;
cout << "Type your name: ";
cin >> name;
cout << "Your name is " << name << endl;
return 0;
}
When you run this code, you see the console ask you to type your name, and then it stops. That’s because it’s waiting for your input. Notice that the insertion point appears immediately after the text "Type your name:"
. That’s because the first cout
statement lacks the usual endl
. It’s normal to leave the insertion point, or cursor, on the same line as the question to avoid confusing the user. Type a name, such as Fred, without spaces and press Enter. The console then looks like this:
Type your name: Fred
Your name is Fred
The first line includes the name you typed, and the second line is whatever appears after you press Enter. Notice what happens: When you type a word and press Enter, the computer places that word in the name
variable, which is a string. Then you can print name
to the console by using cout
.
You can also read integers, as in the following code (in the ReadInt
example):
#include <iostream>
using namespace std;
int main()
{
int x;
cout << "Type your favorite number: ";
cin >> x;
cout << "Your favorite number is " << x << endl;
return 0;
}
This sample code reads a single integer into the variable x
and then prints it to the console.