Problem Solving With C 10Th Edition Savitch Solutions Manual Full Chapter PDF

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 67

Problem Solving with C++ 10th Edition

Savitch Solutions Manual


Visit to download the full and correct content document: https://testbankdeal.com/dow
nload/problem-solving-with-c-10th-edition-savitch-solutions-manual/
Chapter 8

Strings and Vectors

1. Solutions for and Comment on Selected Practice Programs and


Programming Projects

Practice Program 7: Pig Latin


// **********************************************************************
//
// This program converts a name into Pig Latin.
//
//
***********************************************************************

#include <iostream>
#include <string>
#include <cctype>

using namespace std;

// 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;

cout << "Enter your first name." << endl;


cin >> first;
cout << "Enter your last name." << endl;
cin >> last;

pigFirst = convertToPigLatin(first);
pigLast = convertToPigLatin(last);
cout << "Your name in pig latin is: " << pigFirst << " " << pigLast
<< endl;
return 0;
}

Programming Project 1: Format a Sentence.

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

This program is to read in a (single) sentence (defined as a sequence of words terminated


by a period (.). The sentence is to be formatted and written to the output. Formatting
consists of capitalizing first words in a sentence and compressing all multiple blanks to
single blanks. For this purpose, a line-break is a blank. No other capital letters are to be
included in the output. A sentence is assumed end with a period and there are no other
periods.

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>

void get_sentence( char sentence[], int& size);


//Fetches characters for sentence up to a period. The period
//is put at the end of characters fetched. size is set to
//number of characters fetched, including the period.

void process(char str[], int size);


//replaces newline by blanks, compresses multiple blanks to
//one capitalizes the first letter of the first word, lower
//cases rest.

int main()
{

4
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

using namespace std;


char sentence[100];
int size;
cout << "Enter one sentence. The period is the "
<<"sentinel to quit." << endl;
get_sentence( sentence, size);
cout << endl;
cout << sentence << endl;
}

void get_sentence( char sentence[], int& size)


{
int have_blank = false;
int is_first_letter = true;

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

if(' ' == sentence[i] && !have_blank)


have_blank = true;
else if(' ' == sentence[i] && have_blank)
i--;
else if(' ' != sentence[i] && have_blank)
have_blank = false;
}
if(i < 99)
sentence[i+1] = '\0';
else
{
sentence[98] = '.';
sentence[99] = '\0';
}
size = i;
}

/*
A typical run follows:
20:12:13:~/AW$ cat input

noW iS thE TiMe fOr aLl


gOOD MEN TO ComE TO tHe
aId
oF

ThE CounTRY.

6
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

20:12:15:~/AW$ a.out <input


Enter one sentence. The period is the sentinel to quit.

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

Programming Project 2: Count words and letters

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.

For purposes of counting letters, case is immaterial.

Output letters in alphabetic order and only output those letters that occur.

Algorithm development:

The word count is carried out with a state machine.

We enter with our state variable, in_word set to false, and our word count set to 0.

while(input characters is successful)


if we have encountered a blank, newline or a tab,
we set state to false
else if in_word is false,
set state to true
increment word count
lo_case = tolower( in_char);
char_count[ int(lo_case) - int('a') ]++;

cout << word_count << " " words" << endl;


for(i = 0; i < 25; i++)
if(char_count[i] != 0)
cout << char_count[i] << " " << char( i + 'a')
<< endl;

Comments on the letter count code:

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

index = int(character) - int('a')

as each letter is read in, increment the appropriate array element.

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>

// character and word count.

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

for (i = 0; i < 26; i++)


char_count[i] = 0;

while('\n' !=(ch = cin.get()))


{
if(' ' == ch || '\n' == ch || '\t' == ch)
in_word = false;
else if(in_word == false)
{
in_word = true;
word_count++;
}
low_case = tolower( ch);
char_count[ int(low_case) - int('a') ]++;
}

cout << word_count << " words" << endl;


for(i = 0; i < 25; i++)
if(char_count[i] != 0)
cout << char_count[i] << " " << char( i + 'a')
<< endl;
return 0;
}

Programming Project 3: Robust input of doubles

I am using only the features provided by <string.h> or <cstring>.

Get double from input

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:

I broke the problem into three pieces:


get the integer part,
ends with '\n' or
go on to next part with a '.' or 'e' or 'E'

Don't get a fractional part if 'e' or 'E'


get the fractional part,
ends with '\n' or go on to next part with a 'e' or 'E'

get the exponent part.


ends with '\n'

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.

Anything else should stop the program.

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>

void read_and_clean(double & n);


// reads a line of input,
// i) discards all symbols except digits for 'whole part',
// reading '.' goes to next part, '\n' terminates
// ii)discards all symbols except digits for fractional
//part, reading 'e' 'E', goes to next part, '\n' terminates

12
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

//iii)discards all symbols except sign, then digits for


//exponent part
// reading '\n' terminates.

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);
}

void read_and_clean(double & n)

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);
}

if( '\n' == 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);
}

// build the fraction


while(next != 'E' && next != 'e' && next != '\n')
// E or e signals to go to next section to pick up
exponent
{
if((isdigit(next)) && (index < MAX_DBL_DIGITS))
{
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;
}

// assert: If we get here, then 'E' == next || 'e' == next


// put it in!

digit_string[index] = next;
index++;

// There may be a sign next, pick up a character,


//put it in digit_string
cin.get(next);

if('-' == next || '+' == next)


{
digit_string[index] = next;
index++;
cin.get(next);
}
else if('\n' == next)
{ //we have an error. make reasonable repair:
//backup and overwrite the e or E with null
index = index - 1; //generate the double and return it.
digit_string[index] = '\0';
n = atof( digit_string);
return;

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

Programming Project 4: First, Middle and Last Names

I present notes only this problem.

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, middle_initial, .


(period after middle initial)

If the middle name is missing altogether the output should be

last_name, first_name

Notes:

This is easy if there is at least a middle initial. Using three variables,

char first_name[20], middle_name[20], last_name[20];

This works well for most names. The input is:

cin >> first_name >> middle_name >> last_name;

and for output:

cout << last_name << ", "

<< first_name << middle_name[0] << '.'


<< endl;

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

Programming Project 5: Text replacement

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.

If the length is 4, call output(char first_letter) that outputs Love or love


depending on whether the first_letter is uppercase or lower case.

A Simple Minded “Almost Solution”:

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."

But it is a such a simple solution:

#include <iostream>
#include <cctype>

void output_love( char first_letter);


// word has 4 letters, if first_letter is uppercase, output
//Love else output love

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;
}

void output_love( char first_letter)


{
using namespace std;
if(isupper( first_letter))
cout << "Love" ;
else
cout << "love";
}

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>

void break_up(char line[], char list[][80], int & n);


// accepts line of up to 79 characters
// returns in list the succession of null terminated words
// and non alpha character strings between them, also null
//terminated. returns number of words in list in parameter n

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;
}

void break_up(char line[], char list[][80], int & number)


{
// separator is anything not alpha
int i = 0, k = 0, word_number = 0;

while( i < strlen( line))


{
k = 0;
// after the start of the line, line[i] is non-alpha
// extract the next non-alphabetic substring
while(!isalpha(line[i]))
{
list[word_number][k] = line[i];
i++; k++;
}
list[word_number][k] = '\0';
word_number++;
k = 0;
//line[i] is an alphabetic character.
//extract the next alphabetic substring
while(isalpha (line[i]))

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;
}

/* STUB * STUB *STUB *STUB *STUB *STUB *STUB *STUB *


//It is WELL WORTH the trouble to create this stub to get
//the rest of the program running correctly.
void break_up(char line[], char list[][80], int & n)
{
list[0][0] = ' ';
list[0][1] = ' ';
list[0][2] = ' ';
list[0][3] = ' ';
list[0][4] = '\0';

list[1][0] = 'n';
list[1][1] = 'o';
list[1][2] = 'w';
list[1][3] = '\0';

list[2][0] = ' ';


list[2][1] = '\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[4][0] = ' ';


list[4][1] = '\0';

list[5][0] = 'a';
list[5][1] = '\0';

list[6][0] = ' ';


list[6][1] = '\0';

list[7][0] = 'G';
list[7][1] = 'o';
list[7][2] = 'o';
list[7][3] = 'd';
list[7][4] = '\0';

list[8][0] = ' ';


list[8][1] = '\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

list[10][0] = ' ';


list[10][1] = ' ';
list[10][2] = ' ';
list[10][3] = ' ';
list[10][4] = '\0';

n = 11;
}

// END OF STUB***END OF STUB***END OF STUB***END OF STUB

*/

Programming Project 7: Anti-Sexist Language

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.

//if pattern is found in target, this returns index of first


//instance of pattern in target
//otherwise this returns 0 to signal "pattern not found"
int match(string target, string pattern);

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;
}

Programming Project 8: Rewrite Sorting function in Display 7.12

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.

Sorry. What is obvious depends on the reader, and is quite subjective.

26
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

Programming Project 10: Insertion Sort (Project 5, Chapter 7) using Vector


Notes only. This problem asks the student to modify the insertion sort problem from
Project 5 from Chapter 7 by replacing the array and size arguments in the insertion sort
function 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.

Programming Project 11 : Secret Code


// ********************************************************************
// This program decodes the secret message by trying all 100 possible
// keys in the decryption algorithm. This is written using c-strings
// due to their relative ease in processing chars as numbers.
//
// The correct key is 88 and the message is "Attack at dawn!"
//
// Note that only visible ASCII characters are encoded.
// This means that characters in the original, unencrypted text will
// always be coded in the range 32 to 126. Additionally, the \ in the
// encoded text must be escaped with a \
//
***********************************************************************

#include <iostream>
#include <cstdlib>
#include <cctype>

using namespace std;

// 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;

for (i=0; i < strlen(encoded); i++)


{
e = encoded[i];
if ((e - key) < 32)
{
d = e + 127 - 32 - key;
}
else
{
d = e - key;
}
decoded[i] = d;
}
}

// ======================
// main function
// ======================
int main()
{
char encoded[] = ":mmZ\\dxZmx]Zpgy";
char decoded[16];
int i;

decoded[15]='\0'; // Make sure string is null terminated


for (i=1; i<100; i++)
{
decrypt(encoded, decoded, i);
cout << "Key: " << i << " Decoded message: " << decoded <<
endl;
}
return 0;
}

Programming Project 12: AM/PM to 24 hour time


// ********************************************************************
// Write a program that inputs a time from the console. The time should
// be in the format “HH:MM AM” or “HH:MM PM”. Hours may be one or two
// digits, for example, “1:10 AM” or “11:30 PM”. Your program should
// then convert the time into a four digit military time based on a 24
// hour clock. For example, “1:10 AM” would output “0110 hours” and
// “12:30 PM” would output “2330 hours”.

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;
}

void write_military_format(const string& time)


{
string am_pm, hour_string;
int colon_pos, space_pos, hour;

// Find the colon between the hour and minutes, and the space before the
// AM/PM
colon_pos = time.find(":");
space_pos = time.find(" ");

am_pm = time.substr(space_pos + 1, 2);


hour_string = time.substr(0, colon_pos);
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;
}

cout << endl << "In military format, '" << time << "' is '";

if (hour < 10)


{
cout << "0";
}
cout << hour << time.substr(colon_pos + 1, 2);

29
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

cout << " hours'." << endl;


}

// ****************************************************************
// 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;
}

string convert_to_military_format(const string& input_time)


{
string am_pm, hour_string;
int colon_pos, space_pos, hour;

// Declare an array of strings for the hours. There are


// better ways of converting ints to strings, but those
// have not been covered yet in the textbook. It would also be
// possible to
string hours[] = { "00", "01", "02", "03", "04", "05", "06",
"07", "08", "09", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20",
"21", "22", "23" };

// 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(" ");

am_pm = input_time.substr(space_pos + 1, 2);


hour_string = input_time.substr(0, colon_pos);

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;
}

return hours[hour] + input_time.substr(colon_pos + 1, 2);


}

Programming Project 13 : XML Address Book


// ********************************************************************
// a) You are hosting a party in Palmdale, CA. Write a program that
// reads in the address.xml file and outputs the names and addresses of
// everyone in Palmdale. Your program shouldn’t output any of the tag
// information, just the address content.
//
// b) You would like to send an advertising flyer to everyone in zip
// codes 90210 – 90214. Write a program that reads in the address.xml
// file and outputs the names and addresses of everyone whose zip code
// falls within the specified range.
//**********************************************************************

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>

// File Name: search.cpp


// Author:
// Email Address:
// Project Number: Chapter 8 Project 13
// Description: Searches an xml file of addresses for those in a particular
// city or range of zip codes.
//
// This version uses only concepts covered in the chapter.
// (Specifically, it does not use the string::npos constant.)
//
// Last Changed: October 11, 2007

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

// Reads the next contact record, returning true if found or false if no


// more records are available
bool read_next_contact(ifstream &in, string &name, string &street,
string &city, string &state, string &zip);

// Prints the given contact


void print_contact(string &name, string &street,
string &city, string &state, string &zip);

// Prints all of the addresses with the given city


void find_city(char file_name[], char city[]);

// 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);

// Returns true if tofind is a substring of str. Will return false if


// tofind is empty. This is equivalent to:
//
// (str.find(tofind) != string::npos)

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;
}

// Prints all of the addresses with the given city


void find_city(char file_name[], char city_to_find[])
{
ifstream in;
string name, street, city, state, zip;

in.open(file_name);
if (in.fail())
{
cout << "Could not open input file" << endl;
exit(1);
}

while (read_next_contact(in, name, street, city, state, zip))


{
if (city == city_to_find)
{
print_contact(name, street, city, state, zip);
}
}

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);
}

while (read_next_contact(in, name, street, city, state, zip))


{
int zipInt = atoi(zip.c_str());

33
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

if ((zipInt >= zip1) && (zipInt <= zip2))


{
print_contact(name, street, city, state, zip);
}
}

in.close();
}

// Reads the next contact record, returning true if found or false if no


// more records are available
bool read_next_contact(ifstream &in, string &name, string &street,
string &city, string &state, string &zip)
{
string line;
bool result = false;

// Clear the strings


name.erase(0, name.length());
street.erase(0, street.length());
city.erase(0, city.length());
state.erase(0, state.length());
zip.erase(0, zip.length());

// Find the next contact record, or the end of the file


getline(in, line);
while ((! contains(line, "contact")) &&
(! contains(line, "/address_book")))
{
getline(in, line);
}

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;
}

void print_contact(string &name, string &street,


string &city, string &state, string &zip)
{
cout << name << endl;
cout << street << endl;
cout << city << ", " << state << " " << zip << endl << endl;
}

// Returns true if tofind is a substring of str. Will return false if


// tofind is empty.
bool contains(string str, string tofind)
{
// The string class provides an easier way of doing this, but it
// is not discussed in the text. The standard str.find(tofind)
// member function will return a value between 0 and one less than
// the length of the string if tofind is a substring of str. Otherwise,
// find will return the special value string::npos. Hence this
// function could be implemented in a single line as:
//
// return (str.find(tofind) != string::npos);

bool found = false;


int lastPosToCheck = str.length() - tofind.length();

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;
}

ALTERNATE VERSION USING STRING::NPOS

35
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

// File Name: search.cpp


// Author:
// Email Address:
// Project Number: Chapter 8 Project 13 b
// Description: Searches an xml file of addresses for those in a particular
// city or range of zip codes.
//
// This version uses the string::npos constant, which is not
// covered in the chapter, to determine if a string contains
// another string.
//
// Last Changed: October 11, 2007

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

// Reads the next contact record, returning true if found or false if no


// more records are available
bool read_next_contact(ifstream &in, string &name, string &street,
string &city, string &state, string &zip);

// Prints the given contact


void print_contact(string &name, string &street,
string &city, string &state, string &zip);

// Prints all of the addresses with the given city


void find_city(char file_name[], char city[]);

// 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;
}

// Prints all of the addresses with the given city


void find_city(char file_name[], char city_to_find[])
{
ifstream in;
string name, street, city, state, zip;

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

cout << "Could not open input file" << endl;


exit(1);
}

while (read_next_contact(in, name, street, city, state, zip))


{
if (city == city_to_find)
{
print_contact(name, street, city, state, zip);
}
}

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);
}

while (read_next_contact(in, name, street, city, state, zip))


{
int zipInt = atoi(zip.c_str());
if ((zipInt >= zip1) && (zipInt <= zip2))
{
print_contact(name, street, city, state, zip);
}
}

in.close();
}

// Reads the next contact record, returning true if found or false if no


// more records are available
bool read_next_contact(ifstream &in, string &name, string &street,
string &city, string &state, string &zip)
{
string line;
bool result = false;

// Clear the strings


name.erase(0, name.length());
street.erase(0, street.length());
city.erase(0, city.length());
state.erase(0, state.length());
zip.erase(0, zip.length());

// Find the next contact record, or the end of the file


getline(in, line);

37
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

while ((line.find("contact") == string::npos) &&


(line.find("/address_book") == string::npos))
{
getline(in, line);
}

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;
}

void print_contact(string &name, string &street,


string &city, string &state, string &zip)
{
cout << name << endl;
cout << street << endl;
cout << city << ", " << state << " " << zip << endl << endl;
}

Programming Project 14: Split function

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;

vector<string> split(string target, string delimiter);

vector<string> split(string target, string delimeter)


{
int index, lastindex;
vector<string> list;

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;

list = split("10,20,30,40", ",");


for (unsigned int i; i < list.size(); i++)
{
cout << list[i] << endl;
}
list = split("do re mi fa so la ti do", " ");
for (unsigned int i; i < list.size(); i++)
{
cout << list[i] << endl;
}

39
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

char ch;
cin >> ch;
return 0;
}

2. Outline of Topics in the Chapter

8.1 An Array Type for Strings


C-string Values and C-string Variables
Other Functions in <cstring>
C-string Input and Output
C-string-to-Number Conversions and Robust Input

8.2 The Standard string Class


Introduction to the Standard Class string
String Processing with the Class string
Converting between string Objects and C-strings

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

8.1 An Array Type for Strings

C-string Values and C-string Variables

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.

null \0 alert or bell \a


newline \n backslash \\
horizontal tab \t question mark \?
vertical tab \v single quote \'
backspace \b double quote \"
carriage return \r
formfeed \f
octal number \ooo o = octal digit
Hex number \xhhh h = hex digit

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.

Predefined C-string Functions


There is a host of C-string functions. In PJ Plauger's Standard C Library I count 22 such
functions in the string.h. (All of string.h functionality appears in the C++ string
header file.) Most of them are variations on the C-string functions listed in the text, or their
equivalents that move a chunk of raw memory. With just a little care, almost anything you
need to do will be easily done with just the functions in the text.
Any use of these functions requires considerable care to ensure the preconditions for these
functions are met. (See the next section in the text "Defining C-string Functions".) The

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!

With the library function


int strncat(char target[], const char source[], int size);
characters are transferred from source to target overwriting the null terminator in
target. If source is smaller than size, all of the characters are transferred, and target is
null terminated. If source is larger than size, then only size characters are transferred and
the terminating character is not appended to target. An unterminated string is potentially
dangerous.

With the library function

44
Copyright © 2018 Pearson Education, Inc.
Savitch Instructor’s Resource Guide
Problem Solving w/ C++, 10e Chapter 8

int strncpy(char target[], const char source[], int size);


characters are moved to the target overwriting target starting at its first characters. If
source is smaller than size, all the characters of source are transferred including the null
terminator, terminating the C-string in target. The balance of target is accessible to
indexing operations, but is normally not of interest. If C-string in source is larger than size,
then only size characters are transferred and target is left unterminated.

C-string Input and Output;


The I/O Streams library was designed before C-strings, so it behaves as other types built-
into C++, as in
cout << news << “ Wow\n”;
or input,
cin >> a >> b;
If you do use C-strings to receive input you must be certain you have provided enough
room for your input and for the necessary null terminator. In a later section of the chapter,
we find C++ provides a string class that is much safer than C-strings for i/o.

C-string-to-Number Conversions and Robust Input


If you enter a non-digit when you are controlling an input loop like this,
while(cin >> int_variable)
{
// whatever
}
you find that the loop terminates. This causes a bad stream state, and any input loops such
as this become infinite loop results. The ability to provide for robust input is important.

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.

The central authorities were now little July.


inclined to take up cases of sorcery; but it
does not appear that on that account witches ceased to be either
dreaded or punished. Country magistrates and clergy were always to
be found who sympathised with the popular terrors on the subject,
and were ready to exert themselves in bringing witches to justice.
At the village of Torryburn, in the western part of Fife, a woman
called Jean Neilson experienced a tormenting and not very
intelligible ailment, which she chose to attribute to the malpractices
of a woman named Lillias Adie. Adie was accordingly taken up by a
magistrate, and put in prison. On the 29th July, the minister and his
elders met in session, called Lillias before them, and were gratified
with an instant confession, to the effect that she had been a witch for
several years, having met the devil at the side of a ‘stook’ on the
harvest-field, and renounced her baptism to him, not without a
tender embrace, on which occasion she found that his skin was cold,
and observed his feet cloven like those of a stirk. She had also joined
in midnight dances where he was present. Once, at the back of
Patrick Sands’s house in Valleyfield, the festivity was lighted by a
light that ‘came from darkness,’ not so bright as a candle, but
sufficient to let them see each other’s faces, and shew the devil, who
wore a cap covering his ears and neck. Several of the women she saw
on these occasions she now delated as witches. The session met again
and again to hear such recitals, and to examine the newly accused
persons. There was little reported but dance-meetings of the alleged
witches, and conversations with the devil, the whole bearing very
much the character of what we have come to recognise as
hallucinations or spectral illusions. Yet the case of Adie was
considered sufficient to infer the pains of death, and she was burned
within the sea-mark. There were several other solemn meetings of
the session to inquire into the cases of the other women accused by
Adie; but we do not learn with what result.
The extreme length to which this affair was carried may be partly
attributed to the zeal of the minister, the Rev. Allan Logan, who is
said to have been particularly knowing in 1704.
the detection of witches. At the
administration of the communion, he would cast his eye along, and
say: ‘You witch-wife, get up from the table of the Lord,’ when some
poor creature, perhaps conscience-struck with a recollection of
wicked thoughts, would rise and depart, thus exposing herself to the
hazard of a regular accusation afterwards. He used to preach against
witchcraft, and we learn that, in 1709, a woman called Helen Key was
accused before the Torryburn session of using some disrespectful
language about him in consequence. She told a neighbour, it appears,
that on hearing him break out against the witches, she thought him
‘daft’ [mad], and took up her stool and left the kirk. For this she was
convicted of profanity, and ordained to sit before the congregation
and be openly rebuked.[358]
Rather earlier in the year, there was a remarkable outbreak of
diablerie at the small seaport burgh of Pittenweem, in the eastern
part of Fife. Here lived a woman named Beatrix or Beatie Laing,
described as ‘spouse to William Brown, tailor, late treasurer of the
burgh,’ and who must therefore be inferred to have been not quite
amongst the poorer class of people. In a petition from the
magistrates (June 13, 1704) to the Privy Council, it was stated that
Patrick Morton was a youth of sixteen, ‘free of any known vice,’ and
that, being employed by his father to make some nails for a ship
belonging to one of the merchants in Pittenweem, he was engaged at
that work in his father’s smithy, when Beatrix Laing came and
desired him to make some nails for her. He modestly refused,
alleging that he was engaged in another job requiring haste,
whereupon she went away ‘threatening to be revenged, which did
somewhat frighten him, because he knew she was under a bad fame
and reputed for a witch.’
Next day, as he passed Beatrix’s door, ‘he observed a timber vessel
with some water and a fire-coal in it at the door, which made him
apprehend that it was a charm laid for him, and the effects of her
threatening; and immediately he was seized with such a weakness in
his limbs, that he could hardly stand or walk.’ He continued for many
weeks in a languishing condition, in spite of all that physicians could
do for him, ‘still growing worse, having no appetite, and his body
strangely emaciated. About the beginning of May, his case altered to
the worse by his having such strange and 1704.
unusual fits as did astonish all onlookers.
His belly at times was distended to a great height; at other times, the
bones of his back and breast did rise to a prodigious height, and
suddenly fell,’ while his breathing ‘was like to the blowing of a
bellows.’ At other times, ‘his body became rigid and inflexible,
insomuch that neither his arms nor legs could be bowed or moved by
any strength, though frequently tried.’ His senses were ‘benumbed,
and yet his pulse [continued] in good order.’ His head sometimes
turned half about, and no force could turn it back again. He suffered
grievous agonies. His tongue was occasionally drawn back in his
throat, ‘especially when he was telling who were his tormentors.’
Sometimes the magistrates or minister brought these people to his
house, and before he saw them, he would cry out they were coming,
and name them. The bystanders would cover his face, bring in the
women he had accused of tormenting him, besides others, and cause
them to touch him in succession; when he expressed pain as the
alleged tormentors laid their hands upon him, and in the other
instances ‘no effect followed.’ It seemed to the magistrates that the
young man was in much the same condition with ‘that of Bargarran’s
daughter in the west.’
Beatrix, and the other accused persons, were thrown into the jail of
the burgh by the minister and magistrates, with a guard of drunken
fellows to watch over them. Beatrix steadily refused to confess being
a witch, and was subjected to pricking, and kept awake for five days
and nights, in order to bring her to a different frame of mind. Sorely
wounded, and her life a burden to her, she at length was forced, in
order to be rid of the torment, to admit what was imputed to her. It
will thus be observed that the humane practice maintained during
the whole of the late cavalier reigns, of only accepting voluntary
confessions from persons taxed with witchcraft, was no longer in
force. The poor woman afterwards avowing that what she had told
them of her seeing the devil and so forth was false, ‘they put her in
the stocks, and then carried her to the Thieves’ Hole, and from that
transported her to a dark dungeon, where she was allowed no
manner of light, or human converse, and in this condition she lay for
five months.’ During this interval, the sapient magistrates, with their
parish minister, were dealing with the Privy Council to get the
alleged witches brought to trial. At first, the design was entertained
of taking them to Edinburgh for that purpose; but ultimately,
through the humane interference of the Earl of Balcarres and Lord
Anstruther,[359] two members of council 1704.
connected with the district, the poor women
were set at liberty on bail (August 12). This, however, was so much in
opposition to the will of the rabble, that Beatrix Laing was obliged to
decamp from her native town. ‘She wandered about in strange
places, in the extremity of hunger and cold, though she had a
competency at home, but dared not come near her own house for
fear of the fury and rage of the people.’
It was indeed well for this apparently respectable woman that she,
for the meantime, remained at a distance from home. While she was
wandering about, another woman, named Janet Cornfoot, was put in
confinement at Pittenweem, under a specific charge from Alexander
Macgregor, a fisherman, to the effect that he had been beset by her
and two others one night, along with the devil, while sleeping in his
bed. By torture, Cornfoot was forced into acknowledging this fact,
which she afterwards denied privately, under equal terror for the
confession and the retractation. However, her case beginning to
attract attention from some persons of rank and education in the
neighbourhood, the minister seems to have become somewhat
doubtful of it, and by his connivance she escaped. Almost
immediately, an officious clergyman of the neighbourhood
apprehended her again, and sent her back to Pittenweem in the
custody of two men.
Falling there into the hands of the populace, the wretched woman
was tied hard up in a rope, beaten unmercifully, and then dragged by
the heels through the streets and along the shore. The appearance of
a bailie for a brief space dispersed the crowd, but only to shew how
easily the authorities might have protected the victim, if they had
chosen. Resuming their horrible work, the rabble tied Janet to a rope
stretching between a vessel in the harbour and the shore, swinging
her to and fro, and amusing themselves by pelting her with stones.
Tiring at length of this sport, they let her down with a sharp fall upon
the beach, beat her again unmercifully, and finally, covering her with
a door, pressed her to death (January 30, 1705). A daughter of the
unhappy woman was in the town, aware of 1704.
what was going on, but prevented by terror
from interceding. This barbarity lasted altogether three hours,
without any adequate interruption from either minister or
magistrates. Nearly about the same time, Thomas Brown, one of
those accused by the blacksmith, died in prison, ‘after a great deal of
hunger and hardship;’ and the bodies of both of these victims of
superstition were denied Christian burial.
The matter attracted the attention of the Privy Council, who
appointed a committee to inquire into it, but the ringleaders of the
mob had fled; so nothing could be immediately done. After some
time, they were allowed to return to the town free of molestation on
account of the murder. Well, then, might Beatrix Laing dread
returning to her husband’s comfortable house in this benighted
burgh. After a few months, beginning to gather courage, she did
return, yet not without being threatened by the rabble with the fate
of Janet Cornfoot; wherefore it became necessary for her to apply to
the Privy Council for a protection. By that court an order was
accordingly issued to the Pittenweem magistrates, commanding
them to defend her from any tumults, insults, or violence that might
be offered to her.
At the close of this year, George and Lachlan Rattray were in
durance at Inverness, ‘alleged guilty of the horrid crimes of
mischievous charms, by witchcraft and malefice, sorcery or
necromancy.’ It being inconvenient to bring them to Edinburgh for
trial, the Lords of Privy Council issued a commission to Forbes of
Culloden, Rose of Kilravock, ... Baillie, commissary of Inverness, and
some other gentlemen, to try the offenders. The judges, however,
were enjoined to transmit their judgment for consideration, and not
allow it to be put in execution without warrant from the Council.
On the 16th July 1706, a committee of Council took into
consideration the verdict in the case of the two Rattrays, and finding
it ‘agreeable to the probation,’ ordained the men to be executed,
under the care of the magistrates of Inverness, on the last
Wednesday of September next to come. This order is subscribed by
Montrose, Buchan, Northesk, Forfar, Torphichen, Elibank, James
Stewart, Gilbert Elliot, and Alexander Douglas.
The functions of the five Lords Aug. 25.
Commissioners of Justiciary being of the
utmost importance, ‘concerning both the lives and fortunes of her
majesty’s lieges,’ the parliament settled on these officers a salary of
twelve hundred pounds Scots each, being 1704.
[360]
about one hundred pounds sterling.
They had previously had the same income nominally, but being
payable by precept of the commissioners of the treasury, or the cash-
keeper, it was, like most such dues, difficult to realise, and, perhaps,
could scarcely be said to exist.
At this time, the fifteen judges of the Court of Session had each two
hundred pounds sterling per annum, the money being derived from a
grant of £20,000 Scots out of the customs and interest on certain
sums belonging to the court.[361] Five of them, who were lords of the
criminal court also, were, as we here see, endowed with a further
salary, making three hundred in all. The situation of president—‘ane
imployment of great weight, requiring are assiduous and close
application,’ says the second President Dalrymple[362]—had usually,
in addition to the common salary, a pension, and a present of wines
from the Treasury, making up his income to about a thousand a year.
By the grace of Queen Anne, after the Union, the puisne judges of the
Court of Session got £300 a year additional, making five hundred in
all;[363] and this was their income for many years thereafter, the
president continuing to have one thousand per annum. In the
salaries of the same officers at the present day—£3000 to a puisne
civil judge, with expenses when he goes on circuit; £4800 to the
President; and to the Lord Justice-clerk, £4500—we see, as
powerfully as in anything, the contrast between the Scotland of a
hundred and fifty years ago, and the Scotland of our own time.

Patrick Smith professed to have found Aug. 30.


out a secret ‘whereby malt may be dried by
all sorts of fuel, whether coals, wood, or turf, so as to receive no
impression from the smoke thereof, and that in a more short and less
expensive manner than hath been known in the kingdom.’ He
averred that ‘the drink brewn of the said malt will be as clear as white
wine, free of all bad tincture, more relishing and pleasant to the
taste, and altogether more agreeable to human health than the ale
hath been heretofore known in the kingdom.’ Seeing how ‘ale is the
ordinary drink of the inhabitants thereof,’ the public utility of the
discovery was obvious. Patrick announced himself to the Privy
Council as willing to communicate his 1704.
secret for the benefit of the country, if
allowed during a certain term to use it in an exclusive manner, and
sell the same right to others.
Their Lordships granted the desired privilege for nine years.

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.

The family of the Gordons of Gicht have Sep. 16.


already attracted our attention by their
troubles as Catholics under Protestant persecution, and their
tendency to wild and lawless habits. After two generations of silence,
the family comes up again in antagonism to the law, but in the
person of the husband of an heiress. It appears that the Miss Gordon
of Gicht who gave birth to George Lord Byron, was not the first
heiress who married unfortunately.
The heretrix of this period had taken as her husband Alexander
Davidson, younger of Newton, who, on the event, became with his
father (a rich man) bound to relieve the mother of his bride—‘the old
Lady Gicht’—of the debts of the family, in requital for certain
advantages conferred upon him. The mother had married as a
second husband Major-general Buchan, 1704.
who commanded the Cavalier army after
the death of Lord Dundee, till he was defeated by Sir Thomas
Livingstone at Cromdale. By and by, Alexander Davidson, under fair
pretences, through James Hamilton of Cowbairdie, borrowed from
his mother-in-law her copy of the marriage-contract, which had not
yet been registered; and when the family creditors applied for
payment of their debts, he did not scruple to send them, or allow
them to go to the old Lady Gicht and her husband for payment. They,
beginning to feel distressed by the creditors, sought back the copy of
the contract for their protection; but as no entreaty could induce
Davidson to return it to Cowbairdie, they were obliged at last to
prosecute the latter gentleman for its restitution.
Cowbairdie, being at length, at the instance of old Lady Gicht and
her husband, taken upon a legal caption, was, with the messenger,
John Duff, at the Milton of Fyvie, at the date noted, on his way to
prison, when Davidson came to him with many civil speeches,
expressive of his regret for what had taken place. He entreated Duff
to leave Cowbairdie there on his parole of honour, and go and
intercede with General Buchan and his wife for a short respite to his
prisoner, on the faith that the contract should be registered within a
fortnight, which he pledged himself should be done. Duff executed
this commission successfully; but when he came back, Davidson
revoked his promise. It chanced that another gentleman had
meanwhile arrived at the Milton, one Patrick Gordon, who had in his
possession a caption against Davidson for a common debt of a
hundred pounds due to himself. Seeing of what stuff Davidson was
made, he resolved no longer to delay putting this in execution; so he
took Duff aside, and put the caption into his hand, desiring him to
take Gicht, as he was called, into custody, which was of course
immediately done.
In the midst of these complicated proceedings, a message came
from the young Lady Gicht, entreating them to come to the family
mansion, a few miles off, where she thought all difficulties might be
accommodated. The whole party accordingly went there, and were
entertained very hospitably till about two o’clock in the morning
(Sunday), when the strangers rose to depart, and Davidson came out
to see them to horse, as a host was bound to do in that age, but with
apparently no design of going along with them. Duff was not so far
blinded by the Gicht hospitality, as to forget that he would be under a
very heavy responsibility if he should allow Davidson to slip through
his fingers. Accordingly, he reminded the 1704.
laird that he was a prisoner, and must come
along with them; whereupon Davidson drew his sword, and called
his servants to the rescue, but was speedily overpowered by the
messenger and his assistant, and by the other gentlemen present. He
and Cowbairdie were, in short, carried back as prisoners that night to
the Milton of Fyvie.
This place being on the estate of Gicht, Duff bethought him next
day that, as the tenants were going to church, they might gather
about their captive laird, and make an unpleasant disturbance; so he
took forward his prisoners to the next inn, where they rested till the
Sabbath was over. Even then, at Davidson’s entreaty, he did not
immediately conduct them to prison, but waited over Monday and
Tuesday, while friends were endeavouring to bring about an
accommodation. This was happily so far effected, the Earl of
Aberdeen, and his son Lord Haddo, paying off Mr Gordon’s claim on
Davidson, and certain relatives becoming bound for the registration
of the marriage-contract.
From whatever motive—whether, as alleged, to cover a vitiation in
the contract, or merely out of revenge—Davidson soon after raised a
process before the Privy Council against Cowbairdie, Gordon, and
Duff, for assault and private imprisonment, concluding for three
thousand pounds of damages; but after a long series of proceedings,
in the course of which many witnesses were examined on both sides,
the case was ignominiously dismissed, and Davidson decerned to pay
a thousand merks as expenses.[364]

Cash being scarce in the country, a Dec.


rumour arose—believed to be promoted by
malicious persons—that the Privy Council intended by proclamation
to raise the value of the several coins then current. The unavoidable
consequence was a run upon the Bank of Scotland, which lasted
twenty days, and with such severity, that at last the money in its
coffers was exhausted, and payments at the bank were suspended;
being the only stoppage or suspension, properly so called, which has
ever taken place in this venerable institution since its starting in
1695, down to the present day, besides one of an unimportant
character, to be afterwards adverted to. ‘That no person possessed of
bank-notes should be a loser, by having their money lie dead and
useless, the proprietors of the bank, in a general meeting, declared
all bank-notes then current to bear interest from the day that
payments were stopped, until they should 1704.
be called in by the directors in order to
payment.’[365]
The Court of Directors (December 19) Dec. 19.
petitioned the Privy Council to send a
committee to inspect their books, and ‘therein see the sufficiency of
the security to the nation for the bank-notes that are running, and to
take such course as in their wisdom they might think fit, for the
satisfaction of those who might have bank-notes in their hands.’
Accordingly, a committee of Council, which included Lord
Belhaven, the President of the Court of Session, the Lord Advocate,
and the Treasurer-depute, met in the bank-office at two o’clock next
day; and having examined the accounts both in charge and
discharge, found that ‘the bank hath sufficient provisions to satisfy
and pay all their outstanding bills and debts, and that with a
considerable overplus, exceeding by a fourth part at least the whole
foresaid bills and debts, conform to ane abstract of the said account
left in the clerk of Council’s hands for the greater satisfaction of all
concerned.’[366]
This report being, by permission of the Privy Council, printed,
‘gave such universal satisfaction, that payments thereafter were as
current as ever, and no stop in business, everybody taking bank-
notes, as if no stop had been for want of specie, knowing that they
would at last get their money with interest.
‘At this time, the Company thought fit to call in a tenth of stock
[£10,000] from the adventurers, which was punctually paid by each
adventurer [being exactly a duplication of the acting capital, which
was only £10,000 before]; and in less than five months thereafter,
the Company being possessed of a good cash, the directors called in
the notes that were charged with interest, and issued new notes, or
made payments in money, in the option of the possessors of the old
notes. And very soon the affairs and negotiations of the bank went on
as formerly, and all things continued easy until the year 1708.’[367]

Notwithstanding the extreme poverty Dec.


now universally complained of, whenever a
man of any figure or importance died, there was enormous expense
incurred in burying him. On the death, at this time, of Lachlan
Mackintosh of Mackintosh—that is, the chief of the clan Mackintosh
—there were funeral entertainments at his 1704.
mansion in Inverness-shire for a whole
month. Cooks and confectioners were brought from Edinburgh, at
great expense, to provide viands for the guests, and liquors were set
aflowing in the greatest profusion. On the day of the interment, the
friends and dependants of the deceased made a procession, reaching
all the way from Dalcross Castle to the kirk of Petty, a distance of
four miles! ‘It has been said that the expense incurred on this
occasion proved the source of pecuniary embarrassments to the
Mackintosh family to a recent period.’[368]
In the same month died Sir William Hamilton, who had for several
years held the office of a judge under the designation of Lord
Whitelaw, and who, for the last two months of his life, was Lord
Justice-clerk, and consequently, in the arrangements of that period,
an officer of state. It had pleased his lordship to assign the great bulk
of his fortune, being £7000 sterling, to his widow, the remainder
going to his heir, Hamilton of Bangour, of which family he was a
younger son. Lord Whitelaw was buried in the most pompous style,
chiefly under direction of the widow, but, to all appearance, with the
concurrence of the heir, who took some concern in the
arrangements, or at least was held as sanctioning the whole affair by
his presence as chief mourner. The entire expenses were £5189
Scots, equal to £432, 8s. 4d. sterling, being more than two years’
salary of a judge of the Court of Session at that time. The lady paid
the tradesmen’s bills out of her ‘donative,’ which was thought a
singularly large one; but, by and by, marrying again, she raised an
action against Bangour, craving allowance for Lord Whitelaw’s
funeral charges ‘out of her intromission with the executry’—that is,
out of the proceeds of the estate, apart from her jointure. The heir
represented that the charges were inordinate, while his inheritance
was small; but this view of the matter does not appear to have been
conclusive, for the Lords, by a plurality, decided that the funeral
expenses of a deceased person ‘must be allowed to the utmost of
what his character and quality will admit, without regard to what
small part of his fortune may come to his heir.’[369] They did, indeed,
afterwards modify this decision, allowing only just and necessary
expenses; but, what is to our present purpose, they do not appear to
have been startled at the idea of spending as much as two years of a
man’s income in laying him under the soil.
The account of expenses at the funeral of 1704.
a northern laird—Sir Hugh Campbell of
Calder, who died in March 1716—gives us, as it were, the anatomy of
one of these ruinous ceremonials. There was a charge of £55, 15s. ‘to
buy ane cow, ane ox, five kids, two wedders, eggs, geese, turkeys,
pigs, and moorfowl,’ the substantials of the entertainment. Besides
£40 for brandy to John Finlay in Forres, £25, 4s. for claret to John
Roy in Forres, £82, 6s. to Bailie Cattenach at Aberdeen for claret,
and £35 to John Fraser in Clunas for ‘waters’—that is, whisky—there
was a charge by James Cuthbert, merchant, of £407, 8s. 4d. for ‘22
pints brandy at 48s. per pint, 18 wine-glasses, 6 dozen pipes, and 3
lb. cut tobacco, 2 pecks of apples, 2 gross corks, one large pewter
flagon at £6, and one small at £3, currants, raisins, cinnamon,
nutmegs, mace, ginger, confected carvy, orange and citron peel, two
pair black shambo gloves for women,’ and two or three other small
articles. There was also £40 for flour, £39, 12s. to the cooks and
baxters, and ‘to malt brewn from the said Sir Hugh’s death to the
interment, sixteen bolls and ane half,’ £88. [Sir Hugh’s body lay from
the 11th to the 29th March, and during these eighteen days there had
been ale for all comers.] The outlay for ‘oils, cerecloth, and
frankincense,’ used for the body, was £60; for ‘two coffins, tables,
and other work,’ £110, 13s. 4d.; for the hearse and adornments
connected with it (inclusive of ‘two mortheads at 40s. the piece’),
£358. With the expenses for the medical attendant, a suit of clothes
to the minister, and some few other matters, the whole amounted to
£1647, 16s. 4d., Scots money.[370] This sum, it will be observed,
indicates a comparatively moderate funeral for a man of such
eminence; and we must multiply everything by three, in order to
attain a probable notion of the eating, the drinking, and the pomp
and grandeur which attended Lord Whitelaw’s obsequies.
The quantity of liquor consumed at the Laird of Calder’s funeral
suggests that the house of the deceased must have been, on such
occasions, the scene of no small amount of conviviality. It was indeed
expected that the guests should plentifully regale themselves with
both meat and drink, and in the Highlands especially the chief
mourner would have been considered a shabby person if he did not
press them to do so. At the funeral of Mrs Forbes of Culloden, or, to
use the phrase of the day, Lady Culloden, her son Duncan, who
afterwards became Lord President of the 1704.
Court of Session, conducted the festivities.
The company sat long and drank largely, but at length the word
being given for what was called the lifting, they rose to proceed to the
burialground. The gentlemen mounted their horses, the commonalty
walked, and all duly arrived at the churchyard, when, behold, no one
could give any account of the corpse! They quickly became aware
that they had left the house without thinking of that important part
of the ceremonial; and Lady Culloden still reposed in the chamber of
death. A small party was sent back to the house to ‘bring on’ the
corpse, which was then deposited in the grave with all the decorum
which could be mustered in such anti-funereal circumstances.[371]
Strange as this tale may read, there is reason to believe that the
occurrence was not unique. It is alleged to have been repeated at the
funeral of Mrs Home of Billie, in Berwickshire, in the middle of the
eighteenth century.
In our own age, we continually hear of the vice of living for
appearances, as if it were something quite unknown heretofore; but
the truth is, that one of the strongest points of contrast between the
past and the present times, is the comparative slavery of our
ancestors to irrational practices which were deemed necessary to
please the eye of society, while hurtful to the individual. This slavery
was shewn very strikingly in the customs attending funerals, and not
merely among people of rank, but in the humblest grades of the
community. It was also to be seen very remarkably in the custom of
pressing hospitality on all occasions beyond the convenience of
guests, in drinking beyond one’s own convenience to encourage
them, and in the customs of the table generally; not less so in the
dresses and decorations of the human figure, in all of which infinitely
more personal inconvenience was submitted to, under a sense of
what was required by fashion, than there is at the present day.

Roderick Mackenzie, secretary to the 1705. Jan.


African Company, advertised what was
called An Adventure for the Curious—namely, a raffle for the
possession of ‘a pair of extraordinary fine Indian screens,’ by a
hundred tickets at a guinea each. The screens were described as
being on sight at his office in Mylne’s Square, but only by ticket
(price 5d.), in order to prevent that pressure of the mob which might
otherwise be apprehended. In these articles, 1705.
the public was assured, ‘the excellence of art
vied with the wonderfulness of nature,’ for they represented a
‘variety of several kinds of living creatures, intermixed with curious
trees, plants, and flowers, all done in raised, embossed, loose, and
coloured work, so admirably to the life, that, at any reasonable
distance, the most discerning eye can scarcely distinguish those
images from the real things they represent,’ Nothing of the kind, it
was averred, had ever been seen in Scotland before, ‘excepting one
screen of six leaves only, that is now in the palace at Hamilton.’[372]

A general arming being now Jan. 5.


contemplated under the Act of Security, it
became important that arms should be obtained cheaply within the
country, instead of being brought, as was customary, from abroad.
James Donaldson, describing himself as ‘merchant in Edinburgh,’
but identical with the Captain Donaldson who had established the
Edinburgh Gazette in 1699, came forward as an enterpriser who
could help the country in this crisis. He professed to have, ‘after great
pains, found out ane effectual way to make machines, whereby
several parts of the art and calling of smith-craft, particularly with
relation to the making of arms, may be performed without the
strength and labour of men, such as blowing with bellows, boring
with run spindles, beating with hammers, [and] striking of files.’ He
craved permission of the Privy Council to set up a work for the
making of arms in this economical way, with exclusive privileges for
a definite period, as a remuneration.
The Council remitted the matter to the deacon of the smiths, for
his judgment, which was very much putting the lamb’s case to the
wolf’s decision. The worshipful deacon by and by reported that
James Donaldson was well known to possess no mechanic skill,
particularly in smith-work, so that his proposal could only be looked
upon as ‘ane engine to inhaunce a little money to supply his
necessity.’ The ordinary smiths were far more fit to supply the
required arms, and had indeed a right to do so, a right which
Donaldson evidently meant to infringe upon. In short, Donaldson
was an insufferable interloper in a business he had nothing to do
with. The Council gave force to this report by refusing Donaldson’s
petition.
Not satisfied with this decision, Donaldson, a few days later,
presented a new petition, in which he more 1705.
clearly explained the kinds of smith-work
which he meant to facilitate—namely, ‘forging, boring, and beating of
gun-barrels, cutting of files, [and] grinding and polishing of
firearms,’ He exhibited ‘the model of the engine for boring and
polishing of gun-barrels, and demonstrated the same, so that their
lordships commended the same as ingenious and very practicable.’
He further disclaimed all idea of interfering with the privileges of the
hammermen of Edinburgh, his ‘motive being nothing else than the
public good and honour of his country,’ and his intention being to set
up his work in a different place from the capital. What he claimed
was no more than what had been granted to other ‘inventors of
engines and mechanical improvements, as the manufactures for wool
and tow cards, that for gilded leather, the gunpowder manufacture,
&c.’
The Lords, learning that much of the opposition of the
hammermen was withdrawn, granted the privileges claimed, on the
condition that the work should not be set up in any royal burgh, and
should not interfere with the rights of the Edinburgh corporation.

Under strong external professions of Feb. 2.


religious conviction, rigorous Sabbath
observance, and a general severity of manners, there prevailed great
debauchery, which would now and then come to the surface. On this
evening there had assembled a party in Edinburgh, who carried
drink and excitement to such a pitch, that nothing less than a dance
in the streets would satisfy them. There was Ensign Fleming of a
Scots regiment in the Dutch service (son of Sir James Fleming, late
provost of Edinburgh); there were Thomas Burnet, one of the
guards; and John, son of the late George Galbraith, merchant. The
ten o’clock bell had rung, to warn all good citizens home. The three
bacchanals were enjoying their frolic in the decent Lawnmarket,
where there was no light but what might come from the windows of
the neighbouring houses; when suddenly there approaches a sedan-
chair, attended by one or two footmen, one of them carrying a
lantern. It was the Earl of Leven, governor of the Castle, and a
member of the Privy Council, passing home to his aërial lodging.
Most perilous was it to meddle with such a person; but the merry
youths were too far gone in their madness to inquire who it was or
think of consequences; so, when Galbraith came against one of the
footmen, and was warned off, he answered with an imprecation, and,
turning to Fleming and Burnet, told them what had passed. Fleming
said it would be brave sport for them to go 1705.
after the chair and overturn it in the mud;
whereupon the three assailed Lord Leven’s servants, and broke the
lantern. His lordship spoke indignantly from his chair, and Fleming,
drawing his sword, wounded one of the servants, but was quickly
overpowered along with his companions.
The young delinquents speedily became aware of the quality of the
man they had insulted, and were of course in great alarm, Fleming in
particular being apprehensive of losing his commission. After a
month’s imprisonment, they were glad to come and make public
profession of penitence on their knees before the Council, in order to
obtain their liberty.[373]
On a Sunday, early in the same month, four free-living gentlemen,
including Lord Blantyre—then a hot youth of two-and-twenty—drove
in a hackney-coach to Leith, and sat in the tavern of a Mrs Innes all
the time of the afternoon-service. Thereafter they went out to take a
ramble on the sands, but by and by returned to drinking at the tavern
of a Captain Kendal, where they carried on the debauch till eight
o’clock in the evening. Let an Edinburgh correspondent of Mr
Wodrow tell the remainder of the story. Being all drunk—‘when they
were coming back to Edinburgh, in the very street of Leith, they
called furiously to the coachman and post-boy to drive. The fellows, I
think, were drunk, too, and ran in on the side of the causey, dung
down [knocked over] a woman, and both the fore and hind wheel
went over her. The poor woman cried; however, the coach went on;
the woman died in half an hour. Word came to the Advocate to-
morrow morning, who caused seize the two fellows, and hath been
taking a precognition of the witnesses ... it will be a great pity that the
gentlemen that were in the coach be not soundly fined for breach of
Sabbath. One of them had once too great a profession to [make it
proper that he should] be guilty now of such a crime.’[374]
The desire to see these scapegraces punished for what was called
breach of Sabbath, without any regard to that dangerous rashness of
conduct which had led to the loss of an innocent life, is very
characteristic of Mr Wodrow’s style of correspondents.

Donaldson’s paper, The Edinburgh Feb. 19.


Gazette, which had been established in
1699, continued in existence; and in the intermediate time there had
also been many flying broadsides printed 1705.
and sold on the streets, containing accounts
of extraordinary occurrences of a remarkable nature, often
scandalous. The growing inclination of the public for intelligence of
contemporary events was now shewn by the commencement of a
second paper in Edinburgh, under the title of The Edinburgh
Courant. The enterpriser, Adam Boig, announced that it would
appear on Monday, Wednesday, and Friday, ‘containing most of the
remarkable foreign news from their prints, and also the home news
from the ports within this kingdom, when ships comes and goes, and
from whence, which it is hoped will prove a great advantage to
merchants and others within this nation (it being now altogether
neglected).’ Having obtained the sanction of the Privy Council, he, at
the date noted, issued the first number, consisting of a small folio in
double columns, bearing to be ‘printed by James Watson in Craig’s
Close,’ and containing about as much literary matter as a single
column of a modern newspaper of moderate size. There are two
small paragraphs regarding criminal cases then pending, and the
following sole piece of mercantile intelligence: ‘Leith, Feb. 16.—This
day came in to our Port the Mary Galley, David Preshu, commander,
laden with wine and brandy.’ There are also three small
advertisements, one intimating the setting up of post-offices at
Wigton and New Galloway, another the sale of lozenges for the
kinkhost [chincough] at 8s. the box.
The superior enterprise shewn in the conducting of the Courant,
aided, perhaps, by some dexterous commercial management, seems
to have quickly told upon the circulation of the Gazette; and we must
regret, for the sake of an old soldier, that the proprietor of the latter
was unwise enough to complain of this result to the Privy Council,
instead of trying to keep his ground by an improvement of his paper.
He insinuated that Boig, having first undersold him by ‘giving his
paper to the ballad-singers four shillings [4d. sterling] a quire below
the common price, as he did likewise to the postmaster,’ did still ‘so
practise the paper-criers,’ as to induce them to neglect the selling of
the Gazette, and set forth the Courant as ‘preferable both in respect
of foreign and domestic news.’ By these methods, ‘the Courant
gained credit with some,’ though all its foreign news was ‘taken
verbatim out of some of the London papers, and most part out of
Dyer’s Letter and the London Courant, which are not of the best
reputation.’ He, on the other hand, ‘did never omit any domestic
news that he judged pertinent, though he never meddled with
matters that he had cause to believe would 1705.
not be acceptable [flattery to the Privy
Council], nor every story and trifling matter he heard.’
A triumphant answer to such a complaint was but too easy. ‘The
petitioner,’ says Boig, ‘complains that I undersold him; that my
Courant bore nothing but what was collected from foreign
newspapers; and that it gained greater reputation than his Gazette.
As to the first, it was his fault if he kept the Gazette too dear; and I
must say that his profit cannot but be considerable when he sells at
my price, for all my news comes by the common post, and I pay the
postage; whereas John Bisset, his conjunct [that is, partner], gets his
news all by the secretary’s packet free of postage, which is at least
eight shillings sterling a week free gain to them. As to the second, I
own that the foreign news was collected from other newspapers, and
I suppose Mr Donaldson has not his news from first hands more
than I did. But the truth is, the Courant bore more, for it always bore
the home news, especially anent our shipping, which I humbly
suppose was one of the reasons for its having a good report; and Mr
Donaldson, though he had a yearly allowance from the royal burghs,
never touched anything of that nature, nor settled a correspondent at
any port in the kingdom, no, not so much as at Leith. As to the third,
it’s left to your Grace and Lordships to judge if it be a crime in me
that the Courant had a greater reputation than the Gazette.’
Connected, however, with this controversy, was an unlucky
misadventure into which Boig had fallen, in printing in his paper a
petition to the Privy Council from Evander M‘Iver, tacksman of the
Scots Manufactory Paper-mills, and James Watson, printer, for
permission to complete the reprinting of an English book, entitled
War betwixt the British Kingdoms Considered. While these
petitioners thought only of their right to reprint English books ‘for
the encouragement of the paper-manufactory and the art of printing
at home, and for the keeping of money as much as may be in the
kingdom,’ the Council saw political inconvenience and danger in the
book, and every reference to it, and at once stopped both the
Courant, in which the advertisement appeared, and the Gazette,
which piteously as well as justly pleaded that it had in no such sort
offended. It was in the course of this affair that Donaldson
complained of Boig’s successful rivalry, and likewise of an invasion
by another person of his monopoly of burial-letters.
After an interruption of three months, Adam Boig was allowed to
resume his publication, upon giving strong assurance of more
cautious conduct in future. His paper 1705.
continued to flourish for several years. (See
under March 6, 1706.)

In the early part of 1704, the sense of Mar. 5.


indignity and wrong which had been
inspired into the national mind by the Darien disasters and other
circumstances, was deepened into a wrathful hatred by the seizure of
a vessel named the Annandale, which the African Company was
preparing for a trading voyage to India. This proceeding, and the
subsequent forfeiture of the vessel before the Court of Exchequer,
were defensive acts of the East India Company, and there can be
little doubt that they were grossly unjust. In the subsequent autumn,
an English vessel, named the Worcester, belonging to what was
called the Two Million Company (a rival to the East India Company),
was driven by foul weather into the Firth of Forth. It was looked
upon by the African Company as fair game for a reprisal. On the 12th
August, the secretary, Mr Roderick Mackenzie, with a few associates,
made an apparently friendly visit to the ship, and was entertained
with a bowl of punch. Another party followed, and were received
with equal hospitality. With only eleven half-armed friends, he that
evening overpowered the officers and crew, and took the vessel into
his possession. In the present temper of the nation, the act,

You might also like