You are on page 1of 5

56 Chapter 2 Fundamental Data Types

Here is the complete program, ch02/vending.cpp:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
const int PENNIES_PER_DOLLAR = 100;
const int PENNIES_PER_QUARTER = 25;

cout << "Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): ";


int bill_value;
cin >> bill_value;
cout << "Enter item price in pennies: ";
int item_price;
cin >> item_price;

int amount_due = PENNIES_PER_DOLLAR * bill_value - item_price;


int dollar_coins = amount_due / PENNIES_PER_DOLLAR;
amount_due = amount_due % PENNIES_PER_DOLLAR;
int quarters = amount_due / PENNIES_PER_QUARTER;

cout << "Dollar coins: " << setw(6) << dollar_coins << endl
<< "Quarters: " << setw(6) << quarters << endl;
}

Program Run
Enter bill value (1 = $1 bill, 5 = $5 bill, etc.): 5
Enter item price in pennies: 225
Dollar coins: 2
Quarters: 3

WOR KE D E XAM PL E 2 . 2 Computing the Cost of Stamps


This Worked Example uses arithmetic functions to simulate a stamp vending machine.

2.5 Strings
Strings are sequences Many programs process text, not numbers. Text
of characters. consists of characters: letters, numbers, punc-
tuation, spaces, and so on. A string is a sequence
of characters. For example, the string "Harry" is a
sequence of five characters.

Available online at www.wiley.com/college/horstmann.

cfe2_c 02_p29_74.indd 56 10/27/10 2:30 PM


2.5 Strings 57

2.5.1 The string Type


You can define variables that hold strings.
string name = "Harry";
The string type is a part of the C++ standard. To use it, simply include the header file,
<string>:
#include <string>
We distinguish between string variables (such as the variable name defined above) and
string literals (character sequences enclosed in quotes, such as "Harry"). The string
stored in a string variable can change. A string literal denotes a particular string, just
as a number literal (such as 2) denotes a particular number.
Unlike number variables, string variables are guaranteed to be initialized even if
you do not supply an initial value. By default, a string variable is set to an empty
string: a string containing no characters. An empty string literal is written as "". The
definition
string response;

has the same effect as


string response = "";

2.5.2 Concatenation

Use the + operator to


Given two strings, such as "Harry" and "Morgan", you can concatenate them to one
concatenate strings; long string. The result consists of all characters in the first string, followed by all
that is, to put them characters in the second string. In C++, you use the + operator to concatenate two
together to yield a
longer string.
strings. For example,
string fname = "Harry";
string lname = "Morgan";
string name = fname + lname;
results in the string
"HarryMorgan"

What if you’d like the first and last name separated by a space? No problem:
string name = fname + " " + lname;

This statement concatenates three strings: fname, the string literal " ", and lname. The
result is
"Harry Morgan"

2.5.3 String Input


You can read a string from the console:
cout << "Please enter your name: ";
string name;
cin >> name;

cfe2_c 02_p29_74.indd 57 10/27/10 2:30 PM


58 Chapter 2 Fundamental Data Types

When a string is read with the >> operator, only one word is placed into the string
variable. For example, suppose the user types
Harry Morgan
as the response to the prompt. This input consists of two words. After the call cin >>
name, the string "Harry" is placed into the variable name. Use another input statement to
read the second word.

2.5.4 String Functions

The length member


The number of characters in a string is called the length of the string. For example, the
function yields the length of "Harry" is 5. You can compute the length of a string with the length function.
number of characters Unlike the sqrt or pow function, the length function is invoked with the dot notation.
in a string.
That is, you write the string whose length you want, then a period, then the name of
the function, followed by parentheses:
int n = name.length();

A member function is Many C++ functions require you to use this dot notation, and you must memorize
invoked using the (or look up) which do and which don’t. These functions are called member func-
dot notation. tions. We say that the member function length is invoked on the variable name.
Once you have a string, you can extract substrings by using the substr member
function. The member function call
s.substr(start, length)
returns a string that is made from the characters in the string s, starting at character
start, and containing length characters. Here is an example:
string greeting = "Hello, World!";
string sub = greeting.substr(0, 5);
// sub is "Hello"

Use the substr The substr operation makes a string that consists of five characters taken from the
member function to string greeting. Indeed, "Hello" is a string of length 5 that occurs inside greeting. A
extract a substring of curious aspect of the substr operation is the starting position. Starting position 0
a string.
means “start at the beginning of the string”. The first position in a string is labeled 0,
the second one 1, and so on. For example, here are the position numbers in the greet-
ing string:

H e l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12

The position number of the last character (12) is always one less than the length of the
string.
Let’s figure out how to extract the substring "World". Count characters starting at 0,
not 1. You find that W, the 8th character, has position number 7. The string you want is
5 characters long. Therefore, the appropriate substring command is
string w = greeting.substr(7, 5);

H e l l o , W o r l d !
0 1 2 3 4 5 6 7 8 9 10 11 12

cfe2_c 02_p29_74.indd 58 10/27/10 2:30 PM


2.5 Strings 59

If you omit the length, you get all characters from the given position to the end of the
string. For example,
greeting.substr(7)

is the string "World!" (including the exclamation mark).


Here is a simple program that puts these concepts to work. The program asks for
your name and that of your significant other. It then prints out your initials.
The operation first.substr(0, 1) makes a string
consisting of one character, taken from the start of
first. The program does the same for the second.
Then it concatenates the resulting one-character
strings with the string literal "&" to get a string of
length 3, the initials string. (See Figure 4.)

first = R o d o l f o
0 1 2 3 4 5 6
second = S a l l y
0 1 2 3 4

initials = R & S
0 1 2
Initials are formed from the first
Figure 4 Building the initials String letter of each name.

ch02/initials.cpp
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 int main()
7 {
8 cout << "Enter your first name: ";
9 string first;
10 cin >> first;
11 cout << "Enter your significant other's first name: ";
12 string second;
13 cin >> second;
14 string initials = first.substr(0, 1)
15 + "&" + second.substr(0, 1);
16 cout << initials << endl;
17
18 return 0;
19 }

Program Run
Enter your first name: Rodolfo
Enter your significant other's first name: Sally
R&S

cfe2_c 02_p29_74.indd 59 10/27/10 2:30 PM


60 Chapter 2 Fundamental Data Types

Table 8 String Operations


Statement Result Comment

string str = "C"; str is set to "C++" When applied to strings,


str = str + "++"; + denotes concatenation.

string str = "C" + "++"; Error Error: You cannot concatenate


two string literals.

cout << "Enter name: "; name contains "Harry" The >> operator places the next
cin >> name; word into the string variable.
(User input: Harry Morgan)

cout << "Enter name: "; name contains Use multiple >> operators to
cin >> name >> last_name; "Harry", last_name read more than one word.
(User input: Harry Morgan) contains "Morgan"

string greeting = "H & S"; n is set to 5 Each space counts as one
int n = greeting.length(); character.

string str = "Sally"; str2 is set to "all" Extracts the substring of length
string str2 = str.substr(1, 3); 3 starting at position 1. (The
initial position is 0.)

string str = "Sally"; str2 is set to "ally" If you omit the length, all
string str2 = str.substr(1); characters from the position
until the end are included.

string a = str.substr(0, 1); a is set to the initial Extracts the substring of length
letter in str 1 starting at position 0.

string b = str.substr(str.length() - 1); b is set to the last The last letter has position
letter in str str.length() - 1. We need not
specify the length.

SELF CHECK 25. What is the length of the string "C++ Program"?
26. Consider this string variable.
string str = "C++ Program";
Give a call to the substr member function that returns the substring "gram".
27. Use string concatenation to turn the string variable str from Self Check 26 to
"C++ Programming".
28. What does the following statement sequence print?
string str = "Harry";
cout << str.substr(0, 1) + str.substr(str.length() - 1);

29. Give an input statement to read a name of the form “John Q. Public”.

Practice It Now you can try these exercises at the end of the chapter: R2.6, R2.9, P2.12, P2.19.

cfe2_c 02_p29_74.indd 60 10/27/10 2:30 PM

You might also like