C++ Primer Plus 第六版编程练习——第6章

★★★★★备注★★★★★

使用的编译环境为 Visual Studio 2017   

默认省略了如下内容:                           

     #include "stdafx.h"                           
     #include <iostream>                               

     using namespace std;

1、Write a program that reads keyboard input to the @ symbol and that echoes the input except for digits, converting each uppercase character to lowercase, and vice versa. (Don’t forget the cctype family.)

#include <cctype>
int main(int argc, const char *argv[])
{
	int ch;
	cout << "Please enter a character or the string: " << endl;
	while ((ch = cin.get()) != '@')
	{
		if (islower(ch))
			cout << (char)toupper(ch);
		else if (isupper(ch))
			cout << (char)tolower(ch);
		else if (ch == '\n')
			cout << endl;
		else
			continue;
	}

	return 0;
}

2、Write a program that reads up to 10 donation values into an array of double. (Or, if you prefer, use an array template object.) The program should terminate input on non-numeric input. It should report the average of the numbers and also report how many numbers in the array are larger than the average.

#include <array>

int main(int argc, const char *argv[])
{
	array<double, 10> dona = {};
	int count = 0;
	double num = 0;
	double average = 0;
	
	while (count < 10)
	{
		cout << "Please enter the " << count + 1 << " donation value: " << endl;
		if (cin >> num && cin.get() == '\n')
		{
			dona[count++] = num;
			average += num;
		}
		else
			break;			
	}
	if (count == 0)
	{
		cout << "No data!" << endl;
		return 0;
	}
	average = average / count;
	cout << "The average of these donations is: " << average << endl;
	cout << "count = " << count << endl;
	num = 0;
	for (int i = 0; i < count; i++)
	{
		if (dona[i] > average)
			num++;
	}
	cout << "There are " << num << " donatios exceed to the average." << endl;
	
	return 0;
}
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

Please enter a c, p, t, or g: q
Please enter a c, p, t, or g: t

A maple is a tree.

int main(int argc, const char *argv[])
{
	cout << "Please enter one of the following choices:" << endl;
	cout << "c) carnivore           p) pianist" << endl;
	cout << "t) tree                g) game" << endl;
exit:
	cout << "Please enter a c, p, t, or g: ";
	
	char choice;	
	cin >> choice;
	
	switch (choice)
	{
	case 'c':
		cout << "A maple is a carnivore." << endl;
		break;
	case 'p':
		cout << "A maple is a pianist." << endl;
		break;
	case 't':
		cout << "A maple is a  tree." << endl;
		break;
	case 'g':
		cout << "A maple is a game." << endl;
		break;
	default:			
		goto exit;
	}	

	return 0;
}
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!

const int SIZE = 20;
struct bop {
	char fullname[SIZE]; // real name
	char title[SIZE]; // job title
	char bopname[SIZE]; // secret BOP name
	int preference; // 0 = fullname, 1 = title, 2 = bopname
};
int main(int argc, const char *argv[])
{
	cout << "Benevolent Order of Programmers Report\n"
		 << "a. display by name     b. display by title\n" 
		 << "c.display by bopname   d.display by preference\n"
		 << "q. quit" << endl;
	char choice;
	bop member[5] = {
		{"Wimp Macho", "Engineer", "DEMON", 0},
		{"Raki Rhodes", "Junior Programmer", "BOOM", 1},
		{"Celia Laiter", "Scientist", "MIPS", 2},
		{"Hoppy Hipman", "Analyst Trainee", "HITTY", 1},
		{"Pat Hand", "Physicist", "LOOPY", 2},
	};
error:
	cout << "Enter your choice: ";
enter:
	cin >> choice;
	switch (choice)
	{
	case 'a':
		for (int i = 0; i < 5; i++)
			cout << member[i].fullname << endl;
		break;
	case 'b':
		for (int i = 0; i < 5; i++)
			cout << member[i].title << endl;
		break;
	case 'c':
		for (int i = 0; i < 5; i++)
			cout << member[i].bopname << endl;
		break;
	case 'd':
		for (int i = 0; i < 5; i++)
		{ 
			if (member[i].preference == 0)
				cout << member[i].fullname << endl;
			else if (member[i].preference == 1)
				cout << member[i].title << endl;
			else
				cout << member[i].bopname << endl;
		}
		break;
	case 'q':
		goto exit;
	default:
		cout << "Bye!" << endl;
		goto error;
	}
	cout << "Next choice: ";
	goto enter;
exit:
	return 0;
}
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 non-numeric input.

int main(int argc, const char *argv[])
{
	double income, tax;
	cout << "Please enter your income: ";
	while (cin >> income && income >= 0)
	{
		if (income <= 5000)
			tax = 0;
		else if (income <= 15000)
			tax = 0.1 * (income - 5000);
		else if (income <= 35000)
			tax = 1000 + 0.15 * (income - 15000);
		else
			tax = 4000 + 0.2 * (income - 35000);
		cout << "Your tax is: " << tax << endl;
		cout << "Please enter your income: ";
	}
	cout << "Bye!\n";

	return 0;
}

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 <string>
struct charity
{
	string name;
	double money;
};

int main(int argc, const char *argv[])
{
	int number;
	int count = 0;
	cout << "Please enter the number of donator: ";
	cin >> number;
	charity *pt = new charity[number];
	for (int i = 0; i < number; i++)
	{
		cout << "Please enter your name: ";
		cin.get();
		getline(cin, pt[i].name);
		cout << "Please enter the money you are going to donator: ";
		cin >> pt[i].money;
		if (pt[i].money > 10000)
			count++;
	}
	if (count == 0)
		cout << "None(money > 10000)";
	else
	{
		cout << "Grand Patron\n";
		for (int i = 0; i < number; i++)
		{
			if (pt[i].money > 10000)
				cout << pt[i].name << " " << pt[i].money << endl;
		}
	}
	
	return 0;
}
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 <cctype>
int main(int argc, const char *argv[])
{
	int vowel = 0, consonant = 0, other = 0;
	char word[15];

	cout << "Enter words(q to quit): " << endl;
	while (cin >> word)
	{
		if (isalpha(word[0]))
		{
			if (word[0] == 'q' && strlen(word) == 1)
				break;
			else if (word[0] == 'a' || word[0] == 'i'
				|| word[0] == 'u' || word[0] == 'e'
				|| word[0] == '0')
				++vowel;
			else
				++consonant;
		}
		else
			++other;
	}
	cout << vowel << " words beginning with vowels" << endl;
	cout << consonant << " words beginning with consonants" << endl;
	cout << other << " other" << endl;

	return 0;
}

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 <fstream>
#include <cstdlib>

int main(int argc, const char *argv[])
{
	char ch;
	int sum = 0;
	ifstream inFile;;
	inFile.open("C++Plus5.cpp");
	if (!inFile.is_open())
	{
		cout << "Open file failed!" << endl;
		cout << "Program terminating." << endl;
		exit(EXIT_FAILURE);
	}

	inFile >> ch;
	while (inFile.good())
	{
		sum++;
		inFile >> ch;
	}

	if (inFile.eof())
		cout << "End of file reached." << endl;
	else if (inFile.fail())
		cout << "Input terminated by data mismatch." << endl;
	else
		cout << "Input terminated for unknown reason." << endl;

	cout << "There are " << sum << " characters in this file." << endl;
	
	return 0;
}
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 <fstream>
#include <cstdlib>
#include <string>

struct charity
{
	string name;
	double money;
};

int main(int argc, const char *argv[])
{
	string filename;
	ifstream infile;
	cout << "Enter name of data file: ";
	getline(cin, filename);
	infile.open(filename);
	if (!infile.is_open())
	{
		cout << "Open file failed!\n"
			<< "Program terminating." << endl;
		exit(EXIT_FAILURE);
	}

	int number, count = 0;
	infile >> number;
	charity *pt = new charity[number];
	for (int i = 0; i < number; i++)
	{
		infile.get();
		getline(infile, pt[i].name);
		infile >> pt[i].money;
		if (pt[i].money > 10000)
			count++;
	}
	if (count == 0)
		cout << "None(money > 10000)";
	else
	{
		cout << "Grand Patron:" << endl;
		for (int i = 0; i < number; i++)
		{
			if (pt[i].money > 10000)
				cout << pt[i].name << " " << pt[i].money << endl;
		}
	}
	
	delete[] pt;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wenfei11471/article/details/80633106