1. 编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写。(提示:cctype函数系列)
// 6-1
#include <iostream>
int main()
{
using namespace std;
char ch = 0;
cout << "Enter some words: " << endl;
while (cin.get(ch) && ch != '@') { //逐个字母读取
if (isdigit(ch))
continue;
else if (islower(ch))
cout << char(toupper(ch));
else if (isupper(ch))
cout << char(tolower(ch));
else cout << ch;
}
cout << endl;
cout << "Done!\n";
return 0;
}
2. 编写一个程序,最多将10个donation值读入到一个double数组中(或模板类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
// 6-2
#include <iostream>
#include <array>
const unsigned int NUM = 10;
int main()
{
using namespace std;
array<double, NUM> donation;
unsigned int enter = 0;
double total_value = 0.0;
double avg = 0.0;
unsigned int large_avg = 0;
cout << "Please enter up to ten double value, Non-digital to exit: \n";
while (enter < 10 && (cin >> donation[enter])) { //遇到非数字字符时,程序将挂起
total_value += donation[enter];
enter++;
}
avg = total_value / enter;
for (int i = 0; i < enter; i++) {
if (donation[i] > avg)
large_avg++;
}
cout << "The average value is " << avg << ", and there are " << large_avg << " double value large than average value." << endl;
return 0;
}
3. 编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。如果用户使用有效选项之外的字母进行相应,程序将提示用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单的操作。
// 6-3
#include <iostream>
#include <iomanip>
int main()
{
using namespace std;
cout << "Please enter one of the following choices: " << endl;
cout << "c) carnivore \t p) pianist" << endl;
cout << "t) tree \t g) game" << endl;
// cout.flags(ios::left);
// cout << setw(20) << "c) carnivore" << "p) pianist" << endl;
// cout << setw(20) << "t) tree" << "g) game" << endl;
char ch;
bool exit