Professional Documents
Culture Documents
Problem Solving With C 10Th Edition Savitch Solutions Manual Full Chapter PDF
Problem Solving With C 10Th Edition Savitch Solutions Manual Full Chapter PDF
Problem Solving With C 10Th Edition Savitch Solutions Manual Full Chapter PDF
#include <iostream>
#include <string>
#include <cctype>
// Function prototypes
string convertToPigLatin(string s);
// ======================
// convertToPigLatin:
// Returns a new string where the input string "s"
// is converted to pig latin. The first letter is
// capitalized.
// ======================
string convertToPigLatin(string s)
{
char f; // First Letter
if (s.length()>0)
{
f = tolower(s[0]);
if ((f=='a') || (f=='e') || (f=='i') || (f=='o') || (f=='u'))
{
// Capitalize first letter
f = toupper(f);
s[0] = f;
// Add "way" to the end
return (s + "way");
}
1
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
else
{
string rest;
// String minus first char
rest = s.substr(1, s.length()-1);
// Capitalize first letter
rest[0] = toupper(rest[0]);
// Make sure original first letter is lowercase
s[0] = tolower(s[0]);
// New string with rest, first letter, and "ay"
return rest + s.substr(0,1) + "ay";
}
}
else return("");
}
// ======================
// main function
// ======================
int main()
{
string first, last;
string pigFirst, pigLast;
pigFirst = convertToPigLatin(first);
pigLast = convertToPigLatin(last);
cout << "Your name in pig latin is: " << pigFirst << " " << pigLast
<< endl;
return 0;
}
While it may be cleaner to use Standard string class string to do this problem, I chose to
use only the feature of <cstring> (or <string.h>) to do this problem. Students need
to be able to use both string and C-string facilities.
2
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
Input: get a 100 character line. The period is the terminating sentinel.
The process scans the line, capitalizing the first letter in the string, looking for
multiple blanks which it eats, except for one, and newline == blank.
Some questions asked during design:
Do I replace new-lines with blanks?
Answer: Defer this question until later. (Added later: The answer is yes)
What do I do with sentences that are longer than my line width on my output
device?
Answer: Scan for and replace new-lines with blanks before replacing multiple
blanks with one blank, and allow wraps on output.
Output: Copy the modified string to the output.
This solution uses only the C style string features.
The input is taken character by character. If a period (.) is encountered, the loop
terminates.
Process:
First, any new-line characters are replaced by blanks.
Next, all characters are made lower case.
There is a one-time switch to capitalize the first non-blank.
There is a state machine for compressing multiple blanks to single blanks:
If we have a blank and haven't seen one since the last non-blank, set a variable,
have_blank. Next if we see a blank and have_blank is already set, cause
overwriting the current blank with the new one by backing up the index to the
3
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
sentence array by one. Once we read a non-blank, if the have_blank note is set to
true, turn it off.
These pieces, along with replacing the newlines with blanks, serve to compress each
sequence of blanks and newlines to one blank.
Finally, there is the matter of putting in a null if the string is shorter than the limit, and
putting in a period and null if the string is too long.
Note:
An alternative solution is to use a loop around cin >> word, where word is a string
variable. This ignores blanks and newlines. Then process the words much as I have
processed the characters here. Then output the words with a single blank between.
#include <iostream>
#include <cstring>
#include <cctype>
int main()
{
4
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
for(int i = 0;
'.' != (sentence[i] = cin.get()) && i < 100;
i++)
{
if('\n' == sentence[i])
sentence[i] = ' ';
sentence[i] = tolower(sentence[i]);
if( is_first_letter && isalpha(sentence[i]))
{
is_first_letter = false;
sentence[i] = toupper(sentence[i]);
}
5
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
/*
A typical run follows:
20:12:13:~/AW$ cat input
ThE CounTRY.
6
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
Now is the time for all good men to come to the aid of the
country.
20:12:18:~/AW$
7
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
This program reads in a line of text, counts and outputs the number of words in the line and
the number of occurrences of each letter.
Define a word to be a string of letters delimited by white space (blank, newline, tab), a
comma, or a period. Assume that the input consists only of characters and these delimiters.
Output letters in alphabetic order and only output those letters that occur.
Algorithm development:
We enter with our state variable, in_word set to false, and our word count set to 0.
8
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
We run tolower on all characters entered. The data structure for the letter count is a 26-
letter int array with indices in the range 0-25, calculated by
Output of the letter count is a loop running from 0-25, with an if statement that allows
output if the array entry isn't zero.
The word counting results of this agree with the Unix wc utility, and agree with hand
counted simple files. I do not supply test results.
#include <iostream>
#include <cctype>
int main()
{
using namespace std;
int in_word = false;
int word_count = 0;
char ch;
char low_case;
int char_count[26];
int i; //i is declared outside for to avoid warnings
about
//differences between new and old binding rules
for the for
//loop variable.
9
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
10
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
Dump all input illegal for double, manufacture a double, ask if that is right, and if not
repeat the process.
Accept input of a double as a string
Edit string input -- a function like read and clean in Display 8.3, more complex in that this
must cope with a decimal point.
More difficult problem: decide whether the user intends to use the form nn.nn E nnn or
nn.nn e nnn rather than nnnn or nnn.nnn from the input, not by asking!
I am doing the more difficult problem here, since that provides the essence of the simpler
problem as well as this problem.
Planning:
Written after developing the program: I did not understand the need to clear the input with
newline(); before running this function again, so I did not include it. The code ran
once, and accepted no input after that. The new_line() is necessary.
Before telling your students why it is necessary to clear the input before running the loop
again, see if they can figure out why.
11
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
The reason the new_line() is necessary is that anything typed in after the single
character that the last input in main asks for is still out there on the input stream, ready to
be fetched by the next input statement. This includes the newline typed to get the input to
accept, or the rest of the yes.
With regard to the question of clearing input prior to another iteration of the loop, it doesn't
matter whether we use
cin.get(ans);
or
cin >> ans;
All we are fetching is the single character, y or some other character. The rest stay
around to confuse the input if we don't do clear away those characters so that the things we
intend are what the input sees.
To convince the student of this, uncomment the output statements in the newline()
function at the bottom. (To be fair, this is what I did to convince myself. I hope it will
convince the student!)
#include <iostream>
#include <cstdlib>
#include <cctype>
12
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
void new_line();
int main()
{
using namespace std;
double n;
char ans;
do
{
cout << "Enter a double in any legal format."
<< " return terminates. " << endl;
read_ans_clean( n);
cout << "That string converts to the double "
<< n << endl;
cout << " Again? y/n " << endl;
cin.get(ans);
ans = tolower( ans);
new_line();
} while('y' == ans);
}
13
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
{
using namespace std;
const int MAX_DBL_DIGITS = 15; // max no. significant
digits in double
const int ARRAY_SIZE = MAX_DBL_DIGITS + 7;
// digits + decimal + E + sign + up to three digits +
null
char digit_string[ARRAY_SIZE];
char next;
cin.get(next);
int index = 0;
// decimal signals pick up fraction
// E or e signals pick up exponent
while ('.' != next && '\n' != next && 'E' != next && 'e'
!= next)
{
if((isdigit(next)) && (index < MAX_DBL_DIGITS))
{
digit_string[index] = next;
index++;
}
cin.get(next);
}
14
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
{
digit_string[index] = '\0';
n = atof(digit_string);
return;
}
if('.' == next)
{
digit_string[index] = next;
index++;
cin.get(next);
}
if('\n' == next)
{
15
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
digit_string[index] = '\0';
n = atof(digit_string);
return;
}
digit_string[index] = next;
index++;
16
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
int exp_count = 0;
while(next != '\n')
{
if((isdigit(next)) &&
(index < ARRAY_SIZE)&& exp_count < 3)
{
digit_string[index] = next;
exp_count++;
index++;
}
cin.get(next);
}
digit_string[index] = '\0';
n = atof(digit_string);
return;
}
void new_line()
{
using namespace std;
char symbol;
do
{
cin.get(symbol);
} while (symbol != '\n');
}
17
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
Problem Statement:
This program is supposed to accept first name, middle name or initial, then last name.
Even if the middle name is only an initial, an initial followed by a comma, the output
should be
last_name, first_name
Notes:
If the middle name is missing, the program must detect this (strlen), copy the middle
name to the last name, and set the middle name to an empty string (or just arrange not to
print the middle name). Or you can use string class functions.
18
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
This program accepts a line of text. It replaces all four letter words in the string with
"love". If the four letter word is capitalized, the word love should be also. Only capitalize
the first letter of the word.
In developing this, I came upon a very simple minded solution that almost meets the
requirements of the problem. I present that first.
Caveat: This solution collapses all blanks to one blank, and requires that one must enter
the end-of-file character to terminate the input, rather than "accepting a line of text."
#include <iostream>
#include <cctype>
int main()
{
using namespace std;
char word[81];
while(cin >> word)
{
if(strlen(word) == 4)
19
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
output_love( word[0]);
else
cout << word << " ";
}
cout << endl;
}
A “Better” Solution
(Is it better? - It is certainly a more complicated solution. It does meet the requirements of
the problem exactly. However, I have a preference for the simpler solution!)
The following solution accepts a line of input. It uses cin member getline to fetch a
line of input. A function, break_up, separates the non-alphabetic and alphabetic
substrings of the input line into an array of strings. The main part then examines the strings
one at a time and if alphabetic and of length 4, prints 'love' or 'Love' depending on case of
the string being replaced. The main part prints the string intact if it is of length not equal to
4 or it is non-alphabetic.
Note that there is a (commented out) stub included in the break_up function. It was well
worth the trouble to create stubs to properly debug the main part of the program first.
// Text Replacement
20
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
#include <iostream>
#include <cctype>
int main()
{
using namespace std;
char line[80];
char list[80][80]; // space for 80 words of max length 79
int n;
cin.getline(line, 80);
break_up( line, list, n);
int i = 0;
while(i < n)
{
if(4 == strlen( list[i])&& isalpha(list[i][0]))
{
if(isupper(list[i][0]))
cout << "Love";
else if(islower( list[i][0]))
cout << "love";
}
21
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
else
cout << list[i];
i++;
}
cout << endl;
}
22
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
{
list[word_number][k] = line[i];
i++; k++;
}
list[word_number][k] = '\0';
word_number++;
}
number = word_number;
}
list[1][0] = 'n';
list[1][1] = 'o';
list[1][2] = 'w';
list[1][3] = '\0';
23
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
list[3][0] = 'i';
list[3][1] = 's';
list[3][2] = '\0';
list[5][0] = 'a';
list[5][1] = '\0';
list[7][0] = 'G';
list[7][1] = 'o';
list[7][2] = 'o';
list[7][3] = 'd';
list[7][4] = '\0';
list[9][0] = 't';
list[9][1] = 'i';
list[9][2] = 'm';
list[9][3] = 'e';
list[9][4] = '\0';
24
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
n = 11;
}
*/
Notes only. This problem asks for a program that replaces sexist language. It is frequently
easier to solve a problem that is somewhat more general than the problem at hand. My
recommendation is to write a pattern matching function that returns the start index of the
first instance of pattern in target. Then the text to be edited for sexist language would be
traversed for each instance of sexist language, searching and replacing instances as found.
For this project, function arguments should be of type string instead of C-string.
I suggest use of the following obvious(?)1 quadratic matching algorithm. The declaration
follows.
25
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
Algorithm:
int match(string target, string pattern)
{
while(at not end of target)
search for the first character of the pattern in target.
if found
set match to true
increment location
save location
while(not at end of pattern)
if(target[location] != pattern[location])
match = false
break
increment position
if match
return location
reset pattern position to start of pattern
reset location to saved value
return 0;
}
Notes only. This problem asks the student to replace the array and size arguments in the
sort function from Display 7.12 with a vector argument. The vector knows its size, so the
array argument isn't necessary. The actual code will change only to reflect this fact. The
only other changes are namespace issues.
26
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
#include <iostream>
#include <cstdlib>
#include <cctype>
// Function prototypes
void decrypt(char encoded[], char decoded[], int key);
// ======================
// decrypt:
// This function decrypts the input c-string encoded using
// the key and puts it into the c-string decoded.
// The "decoded" c-string must be large enough to hold the
// encoded characters.
// ======================
void decrypt(char encoded[], char decoded[], int key)
27
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
{
int i;
char e,d;
// ======================
// main function
// ======================
int main()
{
char encoded[] = ":mmZ\\dxZmx]Zpgy";
char decoded[16];
int i;
28
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
//
***********************************************************************
#include <iostream>
#include <string>
using namespace std;
// Converts the time in the string to military time. The argument should
// be in "HH:MM AM" or "HH:MM PM" format. The result will be written to
// cout in "hhMM hours" format.
void write_military_format (const string& time);
int main()
{
string input;
cout << "Enter a time in 'HH:MM AM' or 'HH:MM PM' format: ";
getline(cin, input);
write_military_format(input);
return 0;
}
// Find the colon between the hour and minutes, and the space before the
// AM/PM
colon_pos = time.find(":");
space_pos = time.find(" ");
cout << endl << "In military format, '" << time << "' is '";
29
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
// ****************************************************************
// File Name: convertmiltime.cpp
// Author:
// Email Address:
// Project Number: 8.12
// Description: Converts a time in HH:MM AA format to hhMM (military) format.
// This version includes a function that returns a string
// containing the converted time.
// Last Changed: October 10, 2007
#include <iostream>
#include <string>
using namespace std;
// Converts the time in the string to military time. The argument should
// be in "HH:MM AM" or "HH:MM PM" format. The result will be in "hhMM" format.
string convert_to_military_format(const string& input_time);
int main()
{
string input, mil;
cout << "Enter a time in 'HH:MM AM' or 'HH:MM PM' format: ";
getline(cin, input);
mil = convert_to_military_format(input);
cout << endl << "In military format, '" << input << "' is '"
<< mil << " hours'." << endl;
return 0;
}
// Find the colon between the hour and minutes, and the space before the
// AM/PM
colon_pos = input_time.find(":");
space_pos = input_time.find(" ");
30
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
hour = atoi(hour_string.c_str());
if ((am_pm == "PM") || (am_pm == "pm"))
{
if (hour < 12)
{
hour += 12;
}
}
else if (hour == 12) // Midnight is "00"
{
hour = 0;
}
File: Addresses.xml
<?xml version="1.0"?>
<address_book>
<contact>
<name>George Clooney</name>
<street>1042 El Camino Real</street>
<city>Beverly Hills</city>
<state>CA</state>
<zip>90214</zip>
</contact>
<contact>
<name>Cathy Pearl</name>
<street>405 A St.</street>
<city>Palmdale</city>
<state>CA</state>
<zip>93352</zip>
31
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
</contact>
<contact>
<name>Paris Hilton</name>
<street>200 S. Elm St.</street>
<city>Beverly Hills</city>
<state>CA</state>
<zip>90212</zip>
</contact>
<contact>
<name>Wendy Jones</name>
<street>982 Boundary Ave.</street>
<city>Palmdale</city>
<state>CA</state>
<zip>93354</zip>
</contact>
</address_book>
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
// Prints all of the addresses in the given range of zip codes (inclusive)
void find_in_zip_range(char file_name[], int zip1, int zip2);
32
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
//
bool contains(string str, string tofind);
int main()
{
// Look for addresses in Palmdale
cout << "Addresses in Palmdale: " << endl << endl;
find_city("address.xml", "Palmdale");
// Then look for addresses with zip codes between 90210 and 90214
cout << endl << "Addresses with zip codes between 90210 and 90214: "
<< endl << endl;
find_in_zip_range("address.xml", 90210, 90214);
return 0;
}
in.open(file_name);
if (in.fail())
{
cout << "Could not open input file" << endl;
exit(1);
}
in.close();
}
// Prints all of the addresses in the given range of zip codes (inclusive)
void find_in_zip_range(char file_name[], int zip1, int zip2)
{
ifstream in;
string name, street, city, state, zip;
in.open(file_name);
if (in.fail())
{
cout << "Could not open input file" << endl;
exit(1);
}
33
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
in.close();
}
if (! contains(line, "/address_book"))
{
// Keep going until we hit the </contact> tag
getline(in, line);
while (! contains(line, "/contact"))
{
int tagStart = line.find("<");
int tagEnd = line.find(">");
if (contains(line, "<"))
{
string tag = line.substr(tagStart + 1, tagEnd - tagStart - 1);
int closeTag = line.find("</");
string value = line.substr(tagEnd + 1, closeTag - tagEnd - 1);
if (tag == "name")
name = value;
else if (tag == "street")
street = value;
else if (tag == "city")
city = value;
else if (tag == "state")
state = value;
else if (tag == "zip")
zip = value;
}
34
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
getline(in, line);
}
result = true;
}
return result;
}
if (tofind.length() > 0)
{
for (int i = 0; (i <= lastPosToCheck) && (! found); i++)
{
// See if we can find a match for the first character
if (str[i] == tofind[0])
{
// Then iterate through any remaining characters
// in tofind
bool ok = true;
for (int j = 1; (j < tofind.length()) && ok; j++)
{
ok = (str[i + j] == tofind[j]);
}
found = ok;
}
}
}
return found;
}
35
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
// Prints all of the addresses in the given range of zip codes (inclusive)
void find_in_zip_range(char file_name[], int zip1, int zip2);
int main()
{
// Look for addresses in Palmdale
cout << "Addresses in Palmdale: " << endl << endl;
find_city("address.xml", "Palmdale");
// Then look for addresses with zip codes between 90210 and 90214
cout << endl << "Addresses with zip codes between 90210 and 90214: "
<< endl << endl;
find_in_zip_range("address.xml", 90210, 90214);
return 0;
}
in.open(file_name);
if (in.fail())
{
36
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
in.close();
}
// Prints all of the addresses in the given range of zip codes (inclusive)
void find_in_zip_range(char file_name[], int zip1, int zip2)
{
ifstream in;
string name, street, city, state, zip;
in.open(file_name);
if (in.fail())
{
cout << "Could not open input file" << endl;
exit(1);
}
in.close();
}
37
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
if (line.find("/address_book") == string::npos)
{
// Keep going until we hit the </contact> tag
getline(in, line);
while (line.find("/contact") == string::npos)
{
int tagStart = line.find("<");
int tagEnd = line.find(">");
if (tagStart != string::npos)
{
string tag = line.substr(tagStart + 1, tagEnd - tagStart - 1);
int closeTag = line.find("</");
string value = line.substr(tagEnd + 1, closeTag - tagEnd - 1);
if (tag == "name")
name = value;
else if (tag == "street")
street = value;
else if (tag == "city")
city = value;
else if (tag == "state")
state = value;
else if (tag == "zip")
zip = value;
}
getline(in, line);
}
result = true;
}
return result;
}
Instructor Notes: This solution repeatedly finds the target delimeter and uses substr to
extract the current word and put it into a vector.
38
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
// ********************************************************************
//
// Given the following header:
// vector<string> split(string target, string delimiter);
// Implement the function split so that it returns a vector of the
// strings in target that are separated by the string delimiter. For
// example: split("10,20,30", ",")
// should return a vector with the strings “10”, “20”, and “30”.
//**********************************************************************
#include <iostream>
#include <vector>
#include <string>
using namespace std;
lastindex = 0;
index = target.find(delimeter);
while (index != string::npos)
{
// Get substring between lastindex and index
string s = target.substr(lastindex, index - lastindex);
list.push_back(s);
lastindex = index+1;
index = target.find(delimeter, lastindex);
}
// Put the last item into the vector
list.push_back(target.substr(lastindex, target.length() -
lastindex));
return list;
}
int main()
{
vector<string> list;
39
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
char ch;
cin >> ch;
return 0;
}
8.3 Vectors
Vector Basics
Efficiency Issues
3. General Remarks
This chapter treats C-strings, which are essentially partially filled arrays of char, the C++
Standard string, and vector classes.. Because the term string is used in the C++
standard in a pervasive way to mean the Standard string class, we chose to call the
strings that come to C++ through its C heritage, C-strings. We will call a C++ string class
object simply a string.
40
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
A type, as we have seen, is a collection of values and allowable operations. The values that
C-strings can have are things like "Hi, Mom!" These are also called C-string literals. We
know about C-string operations, (copying, concatenation, to mention two) but we don't
presently have any way to implement these in an easily used fashion, and don't have many
details of C-strings. This section of the text provides these details.
Before launching into the text's discussion of C-strings and arrays, some of the details of C
and C++ "escape sequences" or special characters will be presented. The text's discussion
of C-string variables points out that the null character '\0' is the terminator for C-string
variables. The text points out that the library functions that process C-strings (including
the iostreams functions) use the null character as a sentinel indicating the last character of
the C-string. The backslash (\) signals that the next character to be dealt with differently
than it would be handled without the backslash. The backslash is called the escape
character because it escapes the normal meaning of certain characters, allowing them to
have special meaning. The back slash removes or escapes special meaning of characters
that have special meaning. In fact, the backslash removes the escape property of the
backslash itself as well as other characters. For example, to insert a backslash in a C-string,
use \\ in the C-string literal. To insert a so-called double quote, ", into a C-string, use the
escape sequence, \". Here the first backslash escapes the special meaning of the second,
character, backslash or double quote, which is then inserted in the output stream.)
If we just put a 0 into some position in a C-string, the encoding for 0, 48 decimal, or 30
hexadecimal, is stored at that character position. (See the text’s Appendices for the decimal
encoding of the printing ASCII characters.) To get the null character to be stored, we use
the \ before the 0 to escape the usual meaning of 0. This tells the compiler that we want
the numeric value of the null character to be embedded in the C-string. (The value of the
null character really is zero, not the normal encoding of the character 0.)
41
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
C++ provides a number of the 'escape characters'. I have already mentioned \t, the tab
character. It was used to help format output programs from previous chapters. The text
discusses \0 and \n, the null and the new line characters. I include them all here because
many of my students have had problems understanding what happened to certain
characters in their output. I do not advocate giving all this to students, but if you, the
instructor, are aware of these, you are in a better position to help the student when a
problem is encountered.
If you use a backslash in front of a character not mentioned here, the compiler should issue
a warning.
In connection with the remark in the text in the section, C-String Variable Declarations,
and Initializing a C-stringVariable, note that the following statements are not equivalent:
char short_string_a[] = {'a', 'b', 'c'};
and
char short_string_b[] = "abc";
A quick way to convince the student that these are not equivalent is to put these
declarations in a program and send them to the screen. I output an endl after each of
these, I get: "abc" from the first output statement, then "abc" followed by several ugly
42
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
characters, anything in memory up to the next '\0' (if a memory location before the next
null character is read protected, we get a segmentation violation).
If you are running under any version of Linux, you will have od, the octal dump utility.
Running the program then piping the result to od, with the byte by byte output command
line switch (-b), we get
17:28:35:~/AW$ a.out | od -b
0000000 141 142 143 277 320 374 377 277 071 012 141 142
143 012
0000016
17:28:42:~/AW$
The 0000000 is the number (offset from the start) of the first byte, the 141, 142,
and 143 are the octal encoding for 'a', 'b', and 'c'. Following these are
numbers there are 7 octal numbers that are not ASCII characters. They have the 'high bit
set' and generate the PC's extended characters (that I cannot reproduce here). There is
another 141, 142, and 143 that are the output from the second C-string. These are
octal representations for 'a', 'b', and 'c'. The 00000016 is the octal number
for decimal 14. This is the number of a byte that is one past the last number listed on the
previous line.
43
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
section "Pitfall, Dangers in Using string.h" points out that the critical issue is that there
must be space enough in the destination to hold the result.
Here is an additional bit of warning about the strcmp function. I want to expand on the
text's discussion of the strcmp function.
The strcmp function only required to return a positive number if the second string
argument is a C-string argument is lexicographically greater (later in dictionary ordering)
than the first C-string argument, and a negative number if the second C-string argument is
lexicographically earlier than the first C-string argument. For example,
x = strcmp("aaron", "aardvark");
will assign a positive number to x. We note that this is not necessarily 1, though some
implementations indeed do return 1 in this circumstance. If I were implementing strcmp,
I would return the difference of the ASCII value of the first characters that differ in the two
strings. If all the characters were the same, I would return 0.
In fact, in one library I use, strcmp returns the difference of the ASCII encoding values
for the first characters that are different, whereas gnu libc strcmp returns 1 or -1 when
the strings are different. For the example above, one Borland compiler returns 11 while
g++ strcmp returns 1 or -1.
Rule:
Do not write code that depends on +1 or -1 being returned from strcmp!
44
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8
Display 8.3 provides robust input code using C-strings. This code will allow you to test for
all digits and ask for a repeat of the integer input.
One last note on this section: Please be certain the student is aware of the necessity for
providing space for the null terminator when using getline as well as in other C++
45
Copyright © 2018 Pearson Education, Inc.
Another random document with
no related content on Scribd:
This Sir Thomas Dalyell died unmarried, leaving his estates and
baronetcy to a son of his sister Magdalen, grandfather of the present
baronet. The case is cited as shewing the arrangements for a lunatic
man of rank in the days of Queen Anne.
Ever since the year 1691, there had been a Aug. 30.
garrison of government soldiers in
Invergarry House, in Inverness-shire, the residence of Macdonald of
Glengarry. The proprietor esteemed himself a sufferer to the extent
of a hundred and fifty pounds a year, by damages to his lands and
woods, besides the want of the use of his house, which had been
reduced to a ruinous condition; and he now petitioned the
government for some redress, as well as for a removal of the
garrison, the ‘apparent cause’ of planting which had long ago ceased,
‘all that country being still peaceable and quiet in due obedience to
authority, without the least apprehension of disturbance or
commotion.’
The Council ordered Macdonald to be heard in his own cause
before the Lords of the Treasury, in presence of Brigadier Maitland,
governor of Fort-William, that a statement might be drawn up and
laid before the queen. ‘His circumstances,’ however, ‘being such, that
he cannot safely appear before their Lordships without ane personal
protection,’ the Council had to grant a writ discharging all macers
and messengers from putting any captions to execution against him
up to the 20th of September.
Before the time for the conference arrived, the Duke of Argyle put
in a representation making a claim upon Glengarry’s estate, so that it
became necessary to call in the aid of the Lord Advocate to make up
the statement for the royal consideration.