Storing Data in C++ - Introducing C++ - C++ All-in-One For Dummies (2009)

C++ All-in-One For Dummies (2009)

Book I

Introducing C++

Chapter 2: Storing Data in C++

In This Chapter

Using storage bins called variables

Working with integer variables

Using character variables

Manipulating strings

Using Boolean variables

Using conditional operators

Reading from the console

We all love to store things away. Our closets are a perfect example of a place to store things. We have boxes in there that we have not opened in years. Perhaps we 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 computers have two kinds of memory: memory inside the chips and memory in the hard drive. But most people use the term memory in reference to the memory chips; the other is just referred to as the hard drive. When you type a business letter in a word processor, the letter is stored in the memory. After you choose File⇒Save, the letter gets stored to the hard drive, but as long as you still have it 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 closet that we are afraid of. When you write a computer program, you reserve some storage bins, and you give each storage bin a name. You also say what type of thing can go inside the storage bin. The technical term for such a storage bin is a variable.

In this chapter, we show you how you can use these storage bins in your programs.

imageThe programs in this and the remaining chapters work with the free compiler included on this book’s CD-ROM. You can also use any other compiler, such as the C++ compiler supplied with Visual Studio. In this chapter, we’re assuming that (by now) you know how to use the compiler of your choice. Chapter 1 shows you how to use CodeBlocks; to find out more about CodeBlocks see Appendix B.

Putting Your Data Places: Variables

When you write a program, 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 with 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. Minibook I, Chapter 1 advises that a string is simply a bunch of letters, numbers, or other characters all strung together. As for numbers, they can either be integers (which are positive whole numbers, negative whole numbers, and 0) or they can be numbers with a decimal point, such as 3.11 or 10.0, which (for various reasons) are called floating-point numbers.

image The term floating-point number means a number that has a decimal point and something to the right of the decimal point (even if it’s just a 0). When you see the term floating point, you can remember what it means by the word point in its name. Think of decimal point.

image If you are already familiar with the term variable from other fields, be careful that you do not apply their definitions here. Although similar, some significant differences are involved. For example, in algebra, a variable represents an unknown quantity, and you can solve for a variable. But in programming, it’s simpler than that: A variable is simply a storage bin with an associated name.

Creating an integer variable

In your C++ program, you can easily write a line of code that creates a variable. Although what you’re doing at that point is just writing code (and the variable won’t actually get created until you run the program), people often refer to this process as creating a variable. When we are working with another programmer that we like, we will often say, “We’ll go ahead and make a variable.” What we’re really doing is writing code that tells the computer to go ahead and make the variable. And of course, the computer won’t actually make the variable until the program runs. If, on the other hand, we’re working with a programmer we don’t like, we probably won’t say anything at all.

A variable has three aspects, as shown in Table 2-1.

Table 2-1 A Variable Has Three Aspects

Aspect

What It Means

Name

The name you use in your program 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 2-1 in more detail.

Name: Each variable must have a name. In your program, you refer to the variable by this name. For example, you may have a variable called count, and you may have a variable called LastName. Or you could have a variable called MisterGates.

Type: When you create a variable, you must specify the type of information the variable can hold. For example, one variable may hold an integer, and another variable may hold a single character. After you pick a type for the variable in your program, you can put only things of that type into the variable.

Value: At any given moment, a variable holds a single value. For example, an integer variable might hold the number 10, and a character variable might hold the character a. In your program, 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 in Listing 2-1 demonstrates how to create a variable. This is a full program that you can run.

Listing 2-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 2-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, we used the word int. This word is the C++ word for integer. Thus, the variable that we’re declaring can hold an integer. Next is the name of the variable. This variable is calledmynumber. Then a semicolon ends the variable declaration.

Notice that, in this line, we have covered two of the three aspects of variables; we have given the variable a name, and we have told the computer what type of thing we want the variable to hold. The order seems a little odd; in C++, we 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 puts something in the variable. It puts the number 10 in it. Because we already said that the variable can hold an integer, we’re allowed to put in a 10, because it is an integer. If we had tried to put something other than an integer in it, the compiler would have given us an error. The compiler makes sure that we put into a variable only the type of thing that we said we would. It’s good at keeping us in line. And of course, you noticed that the statement ends with a semicolon. In C++, every statement ends with a semicolon.

image To put something in a variable, you type the variable’s name, an equals sign (surrounded by optional spaces), and the value. You then end the line with a semicolon. This line of code is called an assignment. Or you can say that you are setting the variable to the value.

The next line is this:

cout << mynumber << endl;

Minibook I, Chapter 1 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 put a 10 in the storage bin, and so this line will print a 10 on the console. When you run the program, you see this:

10

imageThink of it like this: When you type the variable’s name, you are accessing the variable. The exception to this is when the variable’s name appears to the left of an equals sign. In that case, you are setting the variable.

You can do two things with a variable:

Set the variable: You can set a variable, which means that you can put something inside the storage bin.

Retrieve the value: You can get back the value that is inside the variable. When you do so, the value stays inside it; you are not, so to speak, taking it out.

image When you retrieve the value that is in a variable, you are not removing it from the variable. The value is still inside the variable.

Declaring multiple variables

Many years ago, when we first learned the original C programming language (which was the language that served as the predecessor to C++), we thought it odd that we 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 we want to declare three integer variables in a row, we 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. We have not put anything in any of them, so we 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;

image When you run your programs, the computer executes the statements in the order that they appear in your code. Therefore, in the preceding code, the computer first creates the three storage bins. Then it puts a 10 inside tom. (Now doesn’t that sound yummy.) Next, dick will get a20. And finally, harry will consume a 3254.

Changing values

Although a variable can only hold 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 us of being forgetful, we can just say, “Yes, but you should see that computer we 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 Listing 2-2. Notice that the first part of the program is just like Listing 2-1. But then we added two more lines (shown in bold) that look pretty much like the previous two: The first one sticks something (20) in the same variable as before, and the next one writes it out to the console.

Listing 2-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 we 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.

image When you see a single equals sign by itself, the item on the left side is the variable or item that receives the information that is on the right side.

Setting one variable equal to another

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;

image Although we said copy the value of start into finish, notice that the first thing we typed was finish, and then the equals sign, and then start. Don’t let the language confuse you. The left side of the equals sign is what receives the value; it is an assignment statement.

image When you copy the value of one variable to another the two variables must be the same type. You cannot, for instance, copy the value from a string variable into an integer variable. If you try, the compiler issues an error message and stops.

After the computer runs this copy statement, the two variables hold the same thing. Listing 2-3 is an example of copying one variable to another.

Listing 2-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;

}

Initializing a variable

When you create a variable, it starts out as an empty storage bin. Before it can be of much use, you need to put something in it.

image If you try to retrieve the contents of a variable before you actually put anything in it, you end up with what computer people fondly call unpredictable results. What they really mean to say is, don’t do this because who knows what’s in it. It’s kind of like if you go in the attic and you discover the former owners left a big, ominous box. Do you really want to look inside it? With variables, the problem you run into is that the computer memory has something stored in that particular place where the variable now sits, and that stored item is probably just some number left over from something else. But you can’t know in advance what it is. So always make sure that you place a value inside a variable before you try to retrieve its contents, a process called initializing the variable.

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;

MyThis and MyThat

As you progress through your computer programming life (which is, we hope, in addition to your life as a millionaire), you are likely to notice that, for some reason, some computer programmers seem to favor variable names that start with the word My. Other computer programmers despise this practice and completely distance themselves from it. We have seen such computer identifiers as MyClass, MyNumber, MyHeight, MyName, MyCar, MyWhatASurprise, MyLar, MyStro, and MyOpic. Personally, we have no problem using names that start with My,especially in training exercises.

But the other way is a bit quicker. It looks like this:

int mynumber = 153;

This method combines both worlds into one neat little package that is available for you to use whenever you want. You see us initializing variables both ways in this book, depending on how we feel at the moment.

Creating a great name for yourself

Every variable needs to have a name. But what names can you use? Although you are free to use names such as Fred or Zanzibar or Supercount1000M, there are limits to what you are allowed to use.

image Although most C++ code is in lowercase, you are free to use uppercase letters in your variable names. However, C++ distinguishes between the two. Therefore, if you have a variable called count, you cannot access it later in your program by calling it Count with a capital C. The compiler treats the two names as two different variables, which makes C++ case sensitive. But on the other hand, please don’t use two separate variables in the same program, one called count and one called Count. Although the compiler doesn’t mind, the mere humans that may have to read your code or work on it later might get confused.

Here are the rules you need to follow when creating a variable name:

Characters: You can use any uppercase letter, lowercase letter, number, or underscore in your variable names. Other symbols (such as spaces or the ones above the number keys on your keyboard) are not allowed in variable names. The only catches are that

• The first character cannot be a number.

• The variable name cannot consist of only numbers.

Length: Most compilers these days allow you to have as many characters in the variable name as you want. Just to be sure, and to prove we’re easily amused, in CodeBlocks we successfully created a variable with a name that was over 1000 characters in length. However, we wouldn’t want to have to type that thing over and over. Instead, we recommend keeping your variable names long enough to make sense but short enough that you can type them easily. Most people prefer anywhere from five to ten characters or so.

Examples of acceptable variable names include Count, current_name, address_1000, and LookupAmount. Table 2-2 lists some variable names that are not allowed.

Table 2-2 Examples of Bad Variable Names

Bad Variable Name

Why It’s Not Allowed

12345

It has only numbers (plus 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.

Manipulating Integer Variables

Just like your friends, integer variables can be manipulated. But in this case, manipulation means simply that you can do arithmetic. You can easily do the usual addition, subtraction, multiplication, and division.

In Minibook I, Chapter 1, we introduced the characters that you use for the arithmetic operations. They are

♦ + for addition

♦ - for subtraction

♦ * for multiplication

♦ / for division

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.

image When working with integer variables, remember the two basic things that you can do with variables: You can put something in a variable, and you can retrieve it from a variable. Therefore, when working with an integer variable, the idea is that you can retrieve the contents, do some arithmetic on it, and then print the answer or store it back into the same variable or another variable.

Adding integer variables

If you want to add two integer variables, use the + symbol. You can take the result and either print it or put it back into a variable.

The following 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;

}

This code starts with two integer variables called start and time. It then sets start to 37, and time to 22. Finally, it adds the two variables (to get 59) and prints the results.

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 following code demonstrates this; 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, we declared the integer variable total along with the others. Then, after we stored 37 in start and 22 in time, we added the two and saved the total in the variable called total. Then we finally printed 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 adds 5 to start and saves the new value in total.

image When you use such code as total = start + 5;, although you are adding 5 to start, you are not actually changing the value stored in start. The start variable itself remains the same as it was before this statement runs. Rather, the computer figures out the result ofstart + 5 and saves that value inside total. Thus, total is the only variable that changes here.

Now here’s where things get a little tricky in the logical arena. This might seem a 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, total is a variable in computer programming, and that definition is a bit different from in the math world.

This statement really just means we’re going to add 5 to the value stored in total, and we’ll take the value we get back and store it back in total. In other words, total will now be 5 greater than it was to begin with.

The following code shows this 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 program, you see the following output on the console:

12

17

Notice what took place. First, we put the value 12 inside total and printed the value to the console. Then we added 5 to total, stored that back in total, and printed 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.

imageThink of the total += 5 notation as simply a shortcut for total = total + 5;.

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 it back in total, you can either do this

total = total + time;

or you can use this shortcut:

total += time;

If you are adding just 1 to a variable, you can use an even shorter shortcut. It looks like this:

total++;

This is the same as total = total + 1;.

Table 2-3 summarizes the different things that you can do that involve the addition of variables.

Table 2-3 Doing Things with Addition

What You Can Do

Sample Statement

Add two variables

cout << start + time << endl;

Add a variable and a number

cout << start + 5 << endl;

Add two variables and save the result in a variable

total = start + time;

Add a variable and a number and save the result in a variable

total = start + 5;

Add a number to what’s already in a variable

total = total + 5;

Add a number to what’s already in a variable by using a shortcut

total += 5;

Add a variable to what’s already in a variable

total = total + time;

Add a variable to what’s already in a variable by using a shortcut

total += time;

Add 1 to a variable

total++;

Subtracting integer variables

Everything you can do involving addition of integer variables you can also do with subtraction. For example, you can subtract two variables, as shown in Listing 2-4.

And now the answer to The Great Question

In C++, as well as in the original C language upon which C++ is based, the operator ++ adds 1 to a variable. So this finally brings us to a point where we can answer The Great Question: Where did the name C++ come from? When the guy who originally designed C++, Bjarne Stroustrup, needed a name for his language, he decided to look into its roots for the answer. He had based the language on C; and in C, to add 1 to something, you use the ++ operator. And because he felt that he added only 1 thing to the language, he decided to call the new language C++. Okay, that’s not quite true; he actually added a great deal to the language. But that entire great deal can be thought of as just one thing made of lots of smaller things. What did he add? The main thing of those smaller things is the capability to do object-oriented programming. That’s something we cover in the next chapter. And by the way, the originator of C++, Mr. Stroustrup, is still alive and still doing work for the language at AT&T. You can see his Web page at www.research.att.com/~bs/.

Listing 2-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 program runs, the console shows the number 10, which is 28 - 18. Remember that, as with addition, the value of neither final nor time actually changed. The computer just figured out the difference and printed 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 actually 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 start and saves it back in start:

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 to just subtract one, you can simply use two minus signs, as in

final--;

This is pronounced, minus minus.

Multiplying integer variables

To do multiplication in C++, you use the asterisk (*) symbol. Like addition and subtraction, you can multiply two variables, or you can multiply a variable by a number. You can take the result and either print it or save it in a variable.

For example, you can multiply two variables and print the results to the console with the following:

cout << length * width << endl;

Or you can multiply a variable by a number as in this:

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;

And you can use multiplication to modify a variable’s value, as in the following:

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

total *= 25;

Dividing integer variables

Although addition, subtraction, and multiplication are pretty 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 between 5 people. You just can’t do it. Either somebody will feel cheated, or everyone will get 4, and 1 chip will be left over for everyone to fight over. Of course, you could break every chip into 5 pieces, and then each person gets 1/5 of each chip, but then you’re no longer working with whole numbers — just a bunch of crumbs.

If we use a calculator and type 21 divided by 5, we get 4.2, which is not a whole number. If we want to stick to whole numbers, we have to use the notion of a remainder. In the case of 21 divided by 5, the remainder is 1, as we figured out with the tortilla chips. The reason is that the highest multiple of 5 in 21 is 20 (since 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 our example, 4) is called the quotient. And 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 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 sample program in Listing 2-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 2-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 program, you see the following output:

Dividing 28 by 14.

2

0

Dividing 32 by 6.

5

2

imageNotice, in Listing 2-5, that we used a couple new tricks in addition to (or divided by?) the division tricks. For one, we combined our variable declarations of first and second variables into one statement. A comma separates the variable names, and we wrote the type (int) only once. Next, we combined the output of strings and numbers into a single cout statement. We did this for four of the cout statements. That’s acceptable, as long as you string them together with the << signs between each of them.

You can do all the usual goodies with both the division (/) and remainder (%) 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, as well:

int first = 30;

first /= 5;

cout << first << endl;

In this case, first becomes 6, because 30 / 5 is 6.

int first = 33;

first %= 5;

cout << first << endl;

And in this case, first becomes 3, because the remainder of 33 divided by 6 is 3.

Characters

Another type of variable you can have is a character variable. A character variable can hold a single — just one — character. A character is anything that can be typed, such as the letters of the alphabet, the digits, and the other symbols you see on the computer keyboard.

To use a character variable, you use the type name char. To initialize a character variable, you put your character inside single quotes. (If you use double quotes, the compiler issues an error message.) The following is an example of a character:

char ch;

ch = ‘a’;

cout << ch << endl;

The character variable here is called ch. We initialized it to the character a, which, you notice, is surrounded by single quotes. We then printed it by using cout.

Null character

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; we can’t draw a picture of it in this book for you to hang on your wall. (Bummer.) All we can do is 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’;

Nonprintable and other cool characters

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 will 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, but you can’t type them directly. One example is the newline character. A newline character 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 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 (column 1).

abc

def

What is that symbol?

Never known to turn down the chance to invent a new word, computer people have come up with names for characters that may not always match the names you know. You’ve already heard the use of the word dot for a period when surfing the Internet. And for some characters that already have multiple names, computer folks may use one name and not the other. And sometimes, just to throw you off, they use the usual name for something. The following are some of the names of symbols that computer people like to use:

. dot (but not period or decimal point)

@ at

& ampersand (but not and)

# pound (but not number sign)

! bang, but most people still say exclamation point

~ tilde

% percent

*star (not asterisk)

( left paren or left parenthesis

) right paren or right parenthesis

[ left square bracket or left bracket

] right square bracket or right bracket

== equal-equal (not double equal)

++ plus-plus (not double plus)

- - minus-minus (not double minus)

/ forward slash

\ backslash

{ left brace or left curly brace or open brace

} right brace or right curly brace or close brace

^ caret, but a few people say hat (for real — no joke here!)

“ double quote

Here, we printed abc, then a newline, and then def. Notice that the def continued in the same position it would have been had it been on the first line. For the compilers that we use in this book, however, printing abc, 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 us another special character: the carriage return. (Can you hear the crowd say, “ooooh!”?)

The carriage return 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’ll overwrite what’s already on the line.) That’s true with pretty much every C++ compiler.

In Minibook I, Chapter 1, we describe the tab character 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, which prints the letter a, then a tab, and then the letter b. Notice that, to get the tab character to go into the character variable, we had to use the \ then a t.

char ch = ‘\t’;

cout << “a” << ch << “b” << endl;

In Minibook II, Chapter 1, we mention that to put a double quote inside a string, you needed to precede the double quote with a backslash so 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 the following.

char ch = ‘“‘;

Of course, now that raises an important question: 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 = ‘\\’;

image When the compiler sees a backslash inside a string or a character, it treats the backslash as special and looks at whatever follows it. If you have something like ‘\’ with no other character inside the single quotes following it, the compiler thinks the final quote is to be combined with the backslash. And then it moves forward, expecting a single quote to follow, representing the end. Because a single quote doesn’t appear, the compiler gets confused and issues an error. Compilers are easily confused. Kind of gives you more respect for the human brain.

Strings

If any single computer word has become so common in programming that most computer people forget that it’s a computer word, it would be string. Minibook I, Chapter 1 introduces strings and 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 example program in Listing 2-6 shows you how to use a string variable.

Delimiters limit de tokens

When you read an English sentence, you can tell where one word starts and one word ends by looking at the spaces and the punctuation. The same is true in a computer program. Words are normally separated by spaces, but other characters also denote the beginning and end of a word. With a string, this character is the double quote. Such word dividers are called delimiters (pronounced dee-LIM-it-ers). And just to make sure we stay confused, computer people use the word token to mean the individual words in a program that are set apart by delimiters. However, you won’t hear us use that term again in this book, as we prefer the word word.

Listing 2-6: Using the string Type to Create a String Variable

#include <iostream>

using namespace std;

int main()

{

string mystring;

mystring = “Hello there”;

cout << mystring << endl;

return 0;

}

When you run this program, 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.

Getting a part of a string

Accessing the individual characters within a string is easy. Take a look at Listing 2-7.

Listing 2-7: Using Brackets to Access Individual Characters in a String

#include <iostream>

using namespace std;

int main()

{

string mystring;

mystring = “abcdef”;

cout << mystring[2] << endl;

return 0;

}

Those strange # lines

Now for those strange-looking lines that start with a # symbol. In Minibook I, Chapter 5, we talk about how you can divide your code into multiple pieces, each in its own source file. That is a powerful way to create large software programs, because different people can work on the different parts at the same time. But to do so, somehow each file must know what the other files can do. And the way you tell the files about the other files is by putting a line toward the top of your file that looks like this:

#include <string>

This line means that your program is making use of another file somewhere, and that file has a filename of string. Inside that other file is a bunch of C++ code that essentially gives your program the ability to understand strings. To see this file in CodeBlocks, right-click the filename and choose Open Include File: <filename> from the context menu. The line

#include <iostream>

gives your program the ability to write to the console, among other things. And finally, the line

#include <stdlib.h>

provides some general C++ features that you aren’t yet using. As you progress through C++, you discover more lines that you can include at the top of your program, each starting with #include and each giving your program more features and capabilities. We use many of these throughout this book. Now how is that for a teaser?

Notice that the seventh line, the cout line, has the word mystring followed by a 2 inside brackets. When you run this program, 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? Our eyes may deceive us, but it looks to us like that’s the third character. What gives?

image Turns out, C++ starts numbering the positions inside the string at 0. So for this string, mystring[0] is the first character, which happens to be a. And so really mystring[2] gets the third character. Yes, life gets confusing when trying to hold conversations with programmers, because sometimes they use the phrase the third character to really mean the third position; but sometimes they use it to mean what’s really the fourth position. But to those people, the fourth position is actually the fifth position, which is actually the sixth position. Life among computer programmers can be confusing. In general, in this book, we use fourth position to really mean the fourth position, which you access through mystring[3]. (The number inside brackets is called an index.)

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:

string mystring;

mystring = “abcdef”;

char mychar = mystring[2];

cout << mychar << endl;

In the preceding 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

Changing part of a string

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 1) from a c to a q:

string x = “abcdef”;

x[1] = ‘q’;

cout << x << endl;

This code writes the string aqcdef to the console.

Adding onto a string

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 takes a string and adds a single character onto it:

string mystring;

mystring = “abcdef”;

mystring += ‘g’;

cout << mystring << endl;

This code creates a string with “abcdef”, and then adds a ‘g’ character on to the end to get “abcdefg”. Then it writes the full “abcdefg” to the console.

Adding two strings

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 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 program surrounded by quotes) to an existing string variable, as in the following.

string first = “hello “;

string third = first + “there”;

cout << third << endl;

image You may be tempted to try to add two string constants together, like so:

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 could accomplish the same thing with this code:

string bigstring = “hello there”;

cout << bigstring << endl;

image You can do a lot more with strings. But first, you need to understand something called a function. If you’re curious about functions, read Minibook I, Chapter 4, where we cover all the nitty-gritty details.

Deciding between Conditional Operators

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++ program that can make decisions; see Minibook I, Chapter 3, for a discussion about this topic. But one way that is quite handy is through 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 we have two integer variables, called first and second. first has the value 10 in it, and second has the value 20 in it. We also have a string variable called result. Now, to follow the little process that we just described: Are the two variables equal? No, they are not, so we set result to the string “not equal”.

Now we do this in C++. Look carefully at the following code. First, we are going to declare our variables first, second, and result:

int first = 10;

int second = 20;

string result;

So far, so good. Notice that we didn’t yet initialize the string variable result. But now, we’re going to write a single line of code that performs the process we just described. First, look the following over, and see whether you can figure out what it is doing. Look carefully at the variables and what they may do, based on the process we described earlier. Then we explain what the code does.

result = (first == second) ? “equal” : “not equal”;

This is probably one of the more bizarre looking lines of C++ code you’ll see in this book. First, we’ll tell you what it means. Then we’ll break it into parts to show you why it means what it does.

In English, this means result will get “equal” if first is equal to second; otherwise it will get “not equal”.

So now, break it into two parts. A single equals sign indicates that the left side, result, receives what is on the right side. So we 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 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 the part on the right of the question mark:

“equal” : “not equal”

This is, itself, two pieces divided by a colon. This means that if first is indeed equal to second, result gets the string “equal”. Otherwise, it gets the string “not equal”.

So take a look at the whole thing one more time:

result = (first == second) ? “equal” : “not equal”;

And 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”.

Now here’s the whole program in Listing 2-8.

Listing 2-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;

}

Boolean variables and conditional operators

You can use Boolean variables with conditional operators. In a conditional operator such as

result = (first == second) ? “equal” : “not equal”;

the item (first == second) actually works out to be a Boolean value, either true or false. Therefore, you can break this code up into several lines. We know: Breaking something into several lines seems a little backwards. The reason for breaking code into lines is that sometimes, when you are programming, you may have an expression that is extremely complex, much more complex than first == second. As you grow in your C++ programming ability, you start to build more complex expressions, and then you start to realize just how complex they can become. And often, breaking expressions into multiple smaller pieces is more manageable.

To break this example into multiple lines, you can do the following:

bool isequal;

isequal = (first == second);

result = isequal ? “equal” : “not equal”;

The first line declares a Boolean variable called isequal. The second line sets this to the value first == second. In other words, if first is equal to second, then isequal gets the value true. Otherwise, isequal gets the value false. In the third line, result gets the value “equal” if isequal is true; or result gets the value “not equal” if isequal is false.

The reason that this code works is that the item on the left side of the question mark is a Boolean expression, which is just a fancy way of saying that the code requires a Boolean value. Therefore, you can throw in a Boolean variable if you prefer, because a Boolean variable holds a Boolean value.

Telling the Truth with Boolean Variables

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://en.wikipedia.org/wiki/George_Boole).

The type name for a Boolean variable is bool. Therefore, to declare a Boolean variable, you use a statement like this:

bool finished;

This declares a Boolean variable called finished. Then, you can either put 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 the following

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.

Reading from the Console

Throughout this chapter and the preceding chapter, we have given 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 programs 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 program) uses the cin (pronounced see-in, as in, “When I see out the door, I’m a-seein’ the mountain from here”) object. Next, instead of using the goofy looking << operator, you use the equally but backwardly goofy > operator.

image The << operator is often called an insertion operator because you are writing to (or inserting into) a stream, which is nothing more than a bunch of characters going out somewhere. In the case of cout, those characters are going out to the console. The >> operator, on the other hand, is often called the extraction operator. The idea here is that you are extracting stuff from the stream. In the case of cin, you are pulling letters from the stream that the user is, in a sense, sending into your program through the console.

Listing 2-9 shows how you can read a string from the console.

Listing 2-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, then it stops. That’s because it’s waiting for your input. Notice that the insertion point appears immediately after “Type your name:”. That’s because the first cout statement lacks the usual endl. It’s normal to leave the insertion point, the 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 is the line you typed (or whatever name you chose to go by), and the second line is what appears after you press Enter.

Notice what happened: When you typed a word and pressed Enter, the computer placed that word in the name variable, which is a string. Then you were able to print it to the console by using cout.

You can also read integers, as in the following code:

int x;

cin >> x;

cout << “Your favorite number is “ << x << endl;

This sample code reads a single integer into the variable x and then prints it to the console.

image By default, cin reads in characters from the console based on spaces. If you put spaces in your entry, only the first word gets read. cin reads the second word the next time the program encounters a cin >>.