C++ Primer Plus Chapter 6 Exercise 9

c++IconThe end of chapter 9 concludes with a fairly hefty compilation of some things you have learned thus far. You probably could have simply made a program that grabbed text from a file, but im sure you would still want to associate it with a struct like we have already done. The majority of this program will stay the same as exercise 6 except a couple of additions; one being we create a file stream named “inFile”. We then associate it with a hard-coded file “contrib.txt”, that has our struct info. Then, we check for a file opening error, see if the first line is an integer, and begin grabbing data from the file. This time I use the “new” keyword and make use of the atoi() function to make all this happen. Examine my source to see how I worked through this one:

9. Do Programming Exercise 6, but modify it to get information from a file. The first item
in the file should be the number of contributors, and the rest of the file should consist of
pairs of lines, with the first line of each pair being a contributor’s name and the second
line being a contribution. That is, the file should look like this:
4
Sam Stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000

#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

struct contrib
{
string name;
double amount;
};

int main()
{
// Create input stream
ifstream inFile;
inFile.open("contrib.txt");

// faile-safe
if (!inFile.is_open())
{
cout << "Failed to open: " << inFile << endl;
exit(EXIT_FAILURE);
}

int numDonors = 0;
int patrons = 0;
int grandPatrons = 0;
char lineOne;

cout << "Society for the Preservation of Rightful Influence" << "\n\n";
cout << "Reading File...\n";

(inFile >> lineOne).get();
if(!isdigit(lineOne))
{
cout << "Number of donors not found\n";
return 2;
}
else
cout << "The number of donors is: " << lineOne << "\n\n";

numDonors = atoi(&lineOne);

contrib *society = new contrib[numDonors];

// Gather names and amounts
for(int i = 0; i < numDonors; i++)
{
getline(inFile, society[i].name); // getline to grab names
cout << "Donor # " << (i+1) << " " << society[i].name << endl;
(inFile >> society[i].amount).get();
/*inFile >> society[i].amount;*/
cout << "Amount: " << (i+1) << society[i].amount<< endl;
}

cout << "\n";
// Display donors over 10000
cout << "Grand Patrons: \n";
for(int x = 0; x < numDonors; x++)
{
if(society[x].amount >= 10000)
{
cout << society[x].name << " Donated: "
<< "$ " << society[x].amount << "\n";
grandPatrons = 1;
}
}
if(grandPatrons == 0)
cout << "none\n";

cout << "\n";

// Display all other patrons

cout << "Patrons list: \n";
for(int y = 0; y < numDonors; y++)
{
if(society[y].amount < 10000)
{
cout << society[y].name << " Donated: "
<< "$ " << society[y].amount << "\n";
patrons = 1;
}
}
if(patrons == 0)
cout << "none\n";
delete [] society;

if (inFile.eof())
cout << "End of file reached.\n";
else if (inFile.fail())
cout << "Input terminated by data mismatch.\n";

// free memory
inFile.close();

return 0;
}

C++ Primer Plus Chapter 6 Exercise 8

c++IconWe create a simple file reading program in exercise 8. As usual, there where a couple of ways to accomplish this. I chose to declare my input file, and as long as we did not receive and error opening the file or reach end of file, use isprint to count any characters in the file. Mind you “file.txt” is to be placed in the same directory as your program with some characters in it. See my source below:

8. Write a program that opens a text file, reads it character-by-character to the end of the file, and reports the number of characters in the file.

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

int main()
{
ifstream inFile;
inFile.open("file.txt");

// Fail-safe
if (!inFile.is_open())
{
cout << "Failed to open: " << inFile << endl;
cout << "Kthxby" << endl;
exit(EXIT_FAILURE);
}

char letter;
int count = 0;
inFile >> letter;
while (!inFile.eof())
{
if (isprint(letter))
count++;
inFile >> letter;
}

cout << "\n" << "Number of characters is: " << count << endl;

// Check for EOF
if (inFile.eof())
cout << "End of file found.\n";
else if (inFile.fail())
cout << "Data mismatch.\n";
else
cout << "Input terminated for unknown reason.\n";

// Clean
inFile.close();

cin.get();

return 0;
}

C++ Primer Plus Chapter 6 Exercise 7

c plus plusThere are a number of ways to do exercise 7. My approach uses the switch statement suggestion to keep tabs of vowels. Also, it analyses one word at a time except you have to press enter after each word for it to tally it appropriately. As mentioned, this could be completed multiple ways. Take a look at my solution below:

7.Write a program that reads input a word at a time until a lone q is entered. The program
should then report the number of words that began with vowels, the number that began
with consonants, and the number that fit neither of those categories. One approach is to
use isalpha() to discriminate between words beginning with letters and those that
don’t and then use an if or switch statement to further identify those passing the
isalpha() test that begin with vowels. A sample run might look like this:
Enter words (q to quit):
The 12 awesome oxen ambled
quietly across 15 meters of lawn. q
5 words beginning with vowels
4 words beginning with consonants
2 others

#include <iostream>
#include <string>

using namespace std;

const int size = 50;

int main()
{
char word[size];
int vowels = 0;
int consonants = 0;
int others = 0;

cout << "Enter words (q to quit): ";

while(cin.get(word, size) && (word[0] != 'q' || word[0] != 'Q'))
{
char * ch = new char;
*ch = word[0];

if(isalpha(word[0]))
{
switch(*ch)
{
case 'a' : vowels++;
break;
case 'e' : vowels++;
break;
case 'i' : vowels++;
break;
case 'o' : vowels++;
break;
case 'u' : vowels++;
break;
default  : consonants++;
break;
}
}
else
others++;
cin.get(); // keep grabbing words after enter is pressed
delete ch;
}
cout << vowels << " words beginning with vowels\n"
<< consonants << " words begining with consonants\n"
<< others << " others";

return 0;
}

C++ Primer Plus Chapter 6 Exercise 6

c plus plusExercise 6 has us working with more structs. This time we create a dynamically allocated array of structures. This sounds interesting but is not too difficult after you start putting code to compiler. Essentially, you create your array, declare variables that were mentioned int the text, use the “new” keyword to allow numDonors and our struct, then loop through patrons and their amounts. See my source below for a more clear explanation:

6. Put together a program that keeps track of monetary contributions to the Society for the
Preservation of Rightful Influence. It should ask the user to enter the number of contributors
and then solicit the user to enter the name and contribution of each contributor.
The information should be stored in a dynamically allocated array of structures. Each
structure should have two members: a character array (or else a string object) to store
the name and a double member to hold the amount of the contribution. After reading
all the data, the program should display the names and amounts donated for all donors
who contributed $10,000 or more. This list should be headed by the label Grand
Patrons. After that, the program should list the remaining donors. That list should be
headed Patrons. If there are no donors in one of the categories, the program should print
the word “none.” Aside from displaying two categories, the program need do no sorting.

#include <iostream>
#include <string>

using namespace std;

struct contrib{
string name;
double amount;
};

int main()
{
int numDonors = 0;
int patrons = 0;
int grandPatrons = 0;

cout << "Society for the Preservation of Rightful Influence" << "\n\n";

cout << "Enter number of contributors: ";
cin >> numDonors;
cout << "\n";

contrib *society = new contrib[numDonors];

// Gather names and amounts
for(int i = 0; i < numDonors; i++)
{
cout << "Enter the name of the contributor: ";
cin >> society[i].name;
cout << "Enter the contribution anount: ";
cin >> society[i].amount;
}

cout << "\n";
// Display donors over 10000
cout << "Grand Patrons: \n";
for(int x = 0; x < numDonors; x++)
{
if(society[x].amount >= 10000)
{
cout << society[x].name << " Donated: "
<< "$ " << society[x].amount << "\n";
grandPatrons = 1;
}
}
if(grandPatrons == 0)
cout << "none\n";

cout << "\n";

// Display all other patrons
cout << "Patrons list: \n";
for(int y = 0; y < numDonors; y++)
{
if(society[y].amount < 10000)
{
cout << society[y].name << " Donated: "
<< "$ " << society[y].amount << "\n";
patrons = 1;
}
}
if(patrons == 0)
cout << "none\n";

// free memory
delete [] society;

return 0;
}

C++ Primer Plus Chapter 6 Exercise 5

c plus plusExercise 5 requires we make a looping program to calculate tax, except the tax part is not really conventional. For instance, it is additive throughout different dollar amount. This make our else if structs a little more complicated.  A do-while loop satisfies the requirements of this program nicely, see my source below:

5. The Kingdom of Neutronia, where the unit of currency is the tvarp, has the following
income tax code:
first 5,000 tvarps: 0% tax
next 10,000 tvarps: 10% tax
next 20,000 tvarps: 15% tax
tvarps after 35,000: 20% tax
For example, someone earning 38,000 tvarps would owe 5,000 × 0.00 + 10,000 × 0.10
+ 20,000 × 0.15 + 3,000 × 0.20, or 4,600 tvarps. Write a program that uses a loop to
solicit incomes and to report tax owed. The loop should terminate when the user enters
a negative number or nonnumeric input.

#include <iostream>

using namespace std;

int main()
{
double tvarp = 0.0;
double tax;

do
{
cout << "Enter Tvarps earned this year: \n";
if(tvarp < 0 || !(cin >> tvarp))
{
cout << "Invalid input, non-negative numbers only!\n";
cin.clear();
}
else if (tvarp > 5000 && tvarp <= 15000)
tax = 5000*0 + (tvarp - 5000)*0.10;
else if (tvarp > 15000 && tvarp <= 35000)
tax = 5000*0 + 10000*0.10 + (tvarp - 15000)*0.15;
else if (tvarp > 35000)
tax = 5000*0 + 10000*0.10 + 20000*0.15 + (tvarp - 35000)*0.20;
else tax = 0;

cout << "Your tax is: " << tax << endl;
}
while(tvarp <= 0);

return 0;
}

C++ Primer Plus Chapter 6 Exercise 4

c plus plusIn exercise 4 we step up our menu skills a notch or two. This time, we are using a struct to declare some members and we want to dynamically fill them using an array. Otherwise, this is very similar to exercise 3 in that we are still using switch case. There are some syntactical nuances you must navigate in order to get your output to display correctly and not enter a forever loop. Check out my source below:

4. When you join the Benevolent Order of Programmers, you can be known at BOP meetings
by your real name, your job title, or your secret BOP name. Write a program that
can list members by real name, by job title, by secret name, or by a member’s preference.
Base the program on the following structure:
// Benevolent Order of Programmers name structure
struct bop {
char fullname[strsize]; // real name
char title[strsize]; // job title
char bopname[strsize]; // secret BOP name
int preference; // 0 = fullname, 1 = title, 2 = bopname
};
In the program, create a small array of such structures and initialize it to suitable values.
Have the program run a loop that lets the user select from different alternatives:

a. display by name b. display by title
c. display by bopname d. display by preference
q. quit
Note that “display by preference” does not mean display the preference member; it
means display the member corresponding to the preference number. For instance, if
preference is 1, choice d would display the programmer’s job title. A sample run may
look something like the following:
Benevolent Order of Programmers Report
a. display by name b. display by title
c. display by bopname d. display by preference
q. quit
Enter your choice: a
Wimp Macho
Raki Rhodes
Celia Laiter
Hoppy Hipman
Pat Hand
Next choice: d
Wimp Macho
Junior Programmer
MIPS
Analyst Trainee
LOOPY
Next choice: q
Bye!

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

using namespace std;

// Benevolent Order of Programmers name structure
struct bop {
char fullname[40]; // real name
char title[40]; // job title
char bopname[40]; // secret BOP name
int preference; // 0 = fullname, 1 = title, 2 = bopname
};

void showMenu();

int main()
{
// Initialize struct array
bop programmer[5]={
"Cameron Anglin", "Senior Developer", "rundata", 1,
"Bill Gates", "Quality Assurance", "Bill77", 2,
"Larry Wall", "Debugger", "LW", 0,
"Fusajiro Yamauchi", "Game Tester", "Yoshi", 1,
"Bjarne Stroustrup", "The Creator", "C++", 0
};

showMenu();
char choice;

do
{
cin >> choice;
choice = tolower(choice);
if (choice != 'a' && choice != 'b' && choice !='c' && choice !='d')
continue;
else for(int i = 0; i < 5; i++)
{
switch(choice)
{
case 'a': cout << programmer[i].fullname << "\n";
break;
case 'b': cout << programmer[i].title << "\n";
break;
case 'c': cout << programmer[i].bopname << "\n";
break;
case 'd': switch(programmer[i].preference)
{
case 0: cout << programmer[i].fullname << "\n";
break;
case 1: cout << programmer[i].title << "\n";
break;
case 2: cout << programmer[i].bopname << "\n";
break;
}
}
}
cout << "\n";
showMenu();
}while(choice != 'Q' && choice != 'q');

cout << "Bye!\n";
return 0;
}

void showMenu()
{
cout << "Benevolent Order of Programmers Report\n";
cout <<    "a. display by name      b. display by title\n";
cout <<    "c. display by bopname   d. display by preference\n";
cout <<    "q. quit\n\n";
cout << "Enter your choice: \n";
}

C++ Primer Plus Chapter 6 Exercise 3

c plus plusExercise 3 is interesting because it shows us how a rudimentary menu can be made using simple switch statements. Check out the source for my solution:

3. Write a precursor to a menu-driven program. The program should display a menu offering
four choices, each labeled with a letter. If the user responds with a letter other than
one of the four valid choices, the program should prompt the user to enter a valid
response until the user complies. Then the program should use a switch to select a simple
action based on the user’s selection. A program run could look something like this:
Please enter one of the following choices:
c) carnivore p) pianist
t) tree g) game
f
Please enter a c, p, t, or g: q
Please enter a c, p, t, or g: t
A maple is a tree.

#include <iostream>

using namespace std;

void showMenu();
void carnivore();
void tree();
void pianist();
void game();

int main()
{
char choice;

showMenu();
cin >> choice;
while(choice != 'Q' && choice != 'q')
{
switch(choice)
{
case 'C':
case 'c': carnivore();
break;
case 'P':
case 'p': pianist();
break;
case 'T':
case 't': tree();
break;
case 'G':
case 'g': game();
break;
default: cout << "That is not a choice!\n";
}
showMenu();
cin >> choice;
}
return 0;
}

void showMenu()
{
cout << "Please enter one of the following choices: \n\n";
cout << "c) carnivore p) pianist\n";
cout << "t) tree      g) game\n";
cout << "q) quit\n";
cout << "\n";
}

void carnivore()
{
cout << "Rawr, you have selected carnivore!\n";
}

void tree()
{
cout << "Behold, a tree has spawned!\n";
}

void pianist()
{
cout << "Is this Beethoven?\n";
}

void game()
{
cout << "Shall we play a game?\n";
}