《C++ Primer Plus》(第6版)第6章编程练习
《C++ Primer Plus》(第6版)第6章编程练习
1. 大小写转换
编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写(别忘了cctype函数系列)。
代码:
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char c;
cout << "Enter text for analysis(enter @ to quit):\n";
while (cin >> c && c != '@')
{
if (islower(c))
c = toupper(c);
else if (isupper(c))
c = tolower(c);
if (!isdigit(c))
cout << c;
}
cout << "Done!\n";
system("pause");
return 0;
}
运行结果:
2. 平均值
编写一个程序,最多将10个donation值读入到一个double数组中(如果您愿意,也可使用模板类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
代码:
#include <iostream>
#include <array>
using namespace std;
#define ArrSize 10
int main(void)
{
array<double, ArrSize> donation;
cout << "Enter the elements you want to exist in the array "
<< "( a non number input to terminate):" << endl;
int i = 0;
double sum = 0;
int elem = 0;
int count = 0;
while (i < ArrSize && cin >> donation[i])
{
elem++;
sum += donation[i];
i++;
}
double average = sum / elem;
for (i = 0; i < ArrSize; i++)
{
if (donation[i] > average)
count++;
}
cout << "average = " << average << endl;
cout << count << " numbers greater than average.\n";
system("pause");
return 0;
}
运行结果:
3. 菜单
编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。如果用户使用有效选项之外的字母进行响应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。该程序的运行情况如下:
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;
int main()
{
char ch;
cout << "Please enter one of the following choices:" << endl;
cout << "c) carnivore p) pianist" << endl;
cout << "t) tree g) game" << endl;
while (cin >> ch)
{
switch (ch)
{
case 'c':
cout << "A tiger is a carnivore." << endl;
break;
case 'p':
cout << "Langlang is a pianist." << endl;
break;
case 't':
cout << "A maple is a tree." << endl;
break;
case 'g':
cout << "Golf is a game." << endl;
break;
default:
cout << "Please enter a c, p, t, or g: ";
}
}
system("pause");
return 0;
}
运行结果:
4. 成员
加入 Benevolent Order of Programmer后,在 BOP大会上,人们便可以通过加入者的真实姓名、头衔或秘密BOP姓名来了解他(她)。请编写一个程序,可以使用真实姓名、头衔、秘密姓名或成员偏好来列出成员。编写该程序时,请使用下面的结构:
// 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);
该程序创建一个由上述结构组成的小型数组,并将其初始化为适当的值。另外,该程序使用一个循环,让用户在下面的选项中进行选择:
a. display by name b. display by title
c. display by bopname d. display by preference
q. quit
注意,“display by preference”并不意味着显示成员的偏好,而是意味着根据成员的偏好来列出成员。例如,如果偏好号为1,则选择d将显示程序员的头衔。该程序的运行情况如下:
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
LOOFY
Next choice: q
Bye!
代码:
#include <iostream>
using namespace std;
#define LEN 5
#define strsize 20
// 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);
};
void display_by_name(bop *);
void display_by_title(bop *);
void display_by_bopname(bop *);
void display_by_preference(bop *);
int main()
{
char ch;
bop member[LEN] =
{
{"Wimp Mache", "BOSS", "AS", 0},
{"Raki Rhodes", "Junior Programmer", "MA", 1},
{"Celia Laiter", "Manager", "MIPS", 2},
{"Hoppy Hipman", "Analyst Trainee", "CL", 1},
{"Pat Hand", "Student", "LOOPY", 2}};
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";
cout << "Enter your choice: ";
while (cin >> ch && ch != 'q')
{
switch (ch)
{
case 'a':
display_by_name(member);
break;
case 'b':
display_by_title(member);
break;
case 'c':
display_by_bopname(member);
break;
case 'd':
display_by_preference(member);
break;
}
cout << "Next choice: ";
}
cout << "Bye!\n";
system("pause");
return 0;
}
void display_by_name(bop *b)
{
for (int i = 0; i < LEN; i++)
cout << b[i].fullname << endl;
}
void display_by_title(bop *b)
{
for (int i = 0; i < LEN; i++)
cout << b[i].title << endl;
}
void display_by_bopname(bop *b)
{
for (int i = 0; i < LEN; i++)
cout << b[i].bopname << endl;
}
void display_by_preference(bop *b)
{
for (int i = 0; i < LEN; i++)
{
switch (b[i].preference)
{
case 0:
cout << b[i].fullname << endl;
break;
case 1:
cout << b[i].title << endl;
break;
case 2:
cout << b[i].bopname << endl;
break;
}
}
}
运行结果:
5. 收入所得税
在 Ncutronia王国,货币单位是tvarp,收入所得税的计算方式如下:
5000 tvarps:不收税
5001~15000 tvarps:10%
15001~35000 tvarps:15%
35000 tvarps 以上:20%
例如,收入为38000 tvarps 时,所得税为5000 × 0.00 + 10000 × 0.10 +20000 × 0.15 + 3000 × 0.20,即4600 tvarps。请编写一个程序,使用循环来要求用户输入收入,并报告所得税。当用户输入负数或非数字时,循环将结束。
代码:
#include <iostream>
using namespace std;
#define RATE1 0.10
#define RATE2 0.15
#define RATE3 0.20
double cal_tax(int);
int main()
{
int income;
double tax;
cout << "Enter your income(enter negative number or q to quit): ";
while (cin >> income && income >= 0)
{
cout << "your tax is " << cal_tax(income) <<".\n";
cout << "Enter your income: ";
}
system("pause");
return 0;
}
double cal_tax(int x)
{
double tax;
if (x <= 5000)
tax = 0.0;
else if (x <= 15000)
tax = RATE1 * (x - 5000);
else if (x <= 35000)
tax = RATE1 * (15000 - 5000) + RATE2 * (x - 15000);
else
tax = RATE1 * (15000 - 5000) + RATE2 * (35000 - 15000) + RATE3 * (x - 35000);
return tax;
}
运行结果:
6. 捐款
编写一个程序,记录捐助给“维护合法权利团体”的资金。该程序要求用户输入捐献者数目,然后要求用户输入每一个捐献者的姓名和款项。这些信息被储存在一个动态分配的结构数组中。每个结构有两个成员:用来储存姓名的字符数组(或string对象)和用来存储款项的double成员。读取所有的数据后,程序将显示所有捐款超过10000的捐款者的姓名及其捐款数额。该列表前应包含一个标题,指出下面的捐款者是重要捐款人(Grand Patrons)。然后,程序将列出其他的捐款者,该列表要以Patrons开头。如果某种类别没有捐款者,则程序将打印单词“none”。该程序只显示这两种类别,而不进行排序。
代码:
#include <iostream>
#include <cstring>
using namespace std;
struct Donor
{
string name;
double money;
};
void showGrand(Donor *, int);
void showOther(Donor *, int);
int main()
{
int num = 0;
cout << "How many donors are there? ";
cin >> num;
cin.get(); // 清除缓存
Donor *donor = new Donor[num];
for (int i = 0; i < num; i++)
{
cout << "Please enter the " << i + 1 << "-th name: ";
getline(cin, donor[i].name);
cout << "Please enter the " << i + 1 << "-th money: ";
cin >> donor[i].money;
cin.get();
}
cout << "Grand Patrons:\n";
showGrand(donor, num);
cout << "Patrons:\n";
showOther(donor, num);
system("pause");
return 0;
}
void showGrand(Donor *d, int num)
{
int count = 0;
for (int j = 0; j < num; j++)
{
if (d[j].money > 10000)
{
cout << d[j].name << "\t" << d[j].money << endl;
count++;
}
}
if (count == 0)
cout << "none\n";
}
void showOther(Donor *d, int num)
{
int count = 0;
for (int j = 0; j < num; j++)
{
if (d[j].money <= 10000)
{
cout << d[j].name << "\t" << d[j].money << endl;
count++;
}
}
if (count == 0)
cout << "none\n";
}
运行结果:
7. 统计单词
编写一个程序,它每次读取一个单词,直到用户只输入q。然后,该程序指出有多少个单词以元音打头,有多少个单词以辅音打头,还有多少个单词不属于这两类。为此,方法之一是,使用isalpha( )来区分以字母和其他字符打头的单词,然后对于通过了isalpha()测试的单词,使用if或switch语句来确定哪些以元音打头。该程序的运行情况如下:
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 <cstring>
#include <cctype>
using namespace std;
#define ArrSize 30
int main(void)
{
char str[ArrSize];
int count_other = 0, count_vowel = 0, count_consonant = 0;
cout << "Enter words(q to quit) :" << endl;
while (cin >> str)
{
if (strcmp(str, "q") == 0)
break;
char ch = str[0];
if (isalpha(ch))
{
switch (ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count_vowel++;
break;
default:
count_consonant++;
}
}
else
count_other++;
}
cout << count_vowel << " words beginning with vowels\n";
cout << count_consonant << " words beginning with consonants\n";
cout << count_other << " others\n";
system("pause");
return 0;
}
运行结果:
8. 统计文件字符数
编写一个程序,它打开一个文件文件,逐个字符地读取该文件,直到到达文件末尾,然后指出该文件中包含多少个字符。
代码:
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
#define SIZE 60
int main()
{
char filename[SIZE];
ifstream inFile;
cout << "Enter name of data file:";
cin.getline(filename, SIZE);
inFile.open(filename);
if (!inFile.is_open())
{
cout << "Could not open the file " << filename << endl;
cout << "Program terminating." << endl;
exit(EXIT_FAILURE);
}
int count = 0;
char ch;
inFile >> ch;
while (inFile.good())
{
count++;
inFile >> ch;
// cout << 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 << "A total of " << count << " characters were read." << endl;
inFile.close();
system("pause");
return 0;
}
运行结果:
9. 重写编程练习6
完成编程练习6,但从文件中读取所需的信息。该文件的第一项应为捐款人数,余下的内容应为成对的行。在每一对中,第一行为捐款人姓名,第二行为捐款数额。即该文件类似于下面;
4
sam stone
2000
Freida Flass
100500
Tammy Tubbs
5000
Rich Raptor
55000
代码:
#include <iostream>
#include <cstring>
#include <fstream>
using namespace std;
#define SIZE 30
struct Donor
{
string name;
double money;
};
void showGrand(Donor *, int);
void showOther(Donor *, int);
int main()
{
char fileName[SIZE];
ifstream infile;
int num = 0;
cout << "Enter the filename: ";
cin.getline(fileName, SIZE);
infile.open(fileName);
if (!infile.is_open())
{
cout << "Can't open file " << fileName << endl;
cout << "program terminating." << endl;
exit(EXIT_FAILURE);
}
infile >> num;
infile.get(); // 清除缓存
Donor *donor = new Donor[num];
for (int i = 0; i < num; i++)
{
getline(infile, donor[i].name);
infile >> donor[i].money;
infile.get(); // 清除缓存
}
cout << "Grand Patrons:\n";
showGrand(donor, num);
cout << "Patrons:\n";
showOther(donor, num);
system("pause");
return 0;
}
void showGrand(Donor *d, int num)
{
int count = 0;
for (int j = 0; j < num; j++)
{
if (d[j].money > 10000)
{
cout << d[j].name << "\t" << d[j].money << endl;
count++;
}
}
if (count == 0)
cout << "none\n";
}
void showOther(Donor *d, int num)
{
int count = 0;
for (int j = 0; j < num; j++)
{
if (d[j].money <= 10000)
{
cout << d[j].name << "\t" << d[j].money << endl;
count++;
}
}
if (count == 0)
cout << "none\n";
}
运行结果: