1.编写一个程序,读取键盘输入,直到遇到@符号为止,并回显输入(数字除外),同时将大写字符转换为小写,将小写字符转换为大写(别忘了cctype系列)
using namespace std;
int main()
{
char ch;
cout << "Please enter a string: ";
while (cin >> ch && ch != '@')
{
if (!isdigit(ch))//判断数字
{
if (islower(ch))//判断小写字母
{
ch -= 32;//转换成小写字母
}
else if (isupper(ch))//判断大写字母
{
ch += 32;//转换成小写字母
}
cout << ch;
}
}
cout << endl;
system("pause");
return 0;
}
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
char ch;
cout << "请输入一些字符,以“@”为结束符,若输入字母,大小写将会转换:" << endl;
cin >> ch;
for (; ch != '@';)//遇到第一个字符'@'后结束输入
{
if (isalpha(ch))//如果是字母
{
if (islower(ch))//如果是小写字母
{
ch -= 32;
cout << ch;
}
else if (isupper(ch))
{
ch += 32;
cout << ch;
}
}
else if (!isdigit(ch))//如果是数字
continue;
cin >> ch;
}
system("pause");
return 0;
}
2.编写一个程序,最多将10个donation值读入到一个double数组中(如果您愿意,也可以使用模板类array)。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值。
#include <iostream>
using namespace std;
const int MAX = 10;
int main()
{
double arr[MAX];
double number;
double total = 0;
int i = 0;
cout << "Please enter a number: ";
while (i<MAX&&cin >> number) {
arr[i] = number;
total += number;
i++;
if (i < MAX)
cout << "Please enter a number: ";
}
double average = total / i;
cout << "The average of those numbers is " << average << endl;
int high = 0;
for (int j = 0; j < i; j++)
{
if (arr[j] > average)
high++;
}
cout << "The number of higher than average is " << high << endl;
system("pause");
return 0;
}```
3.编写一个菜单驱动程序的雏形。该程序显示一个提供4个选项的菜单——每个选项用一个字母标记。如果用户使用有效选项之外的字母进行响应,程序将提供用户输入一个有效的字母,直到用户这样做为止。然后,该程序使用一条switch语句,根据用户的选择执行一个简单操作。该程序的运行情况如下:
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.
```cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
char ch;
string c = "carnivore";
string p = "pianist";
string t = "tree";
string g = "game";
cout << "Please enter one of the following choices: " << endl;
cout << "c) " << c << " " << "p)" << p << endl;
cout<< "t) " << t << " " << "g)" << g << endl;
while (cin >> ch && ch != 'c'&&ch != 'p'&&ch != 't'&&ch != 'g')
{
cout << "Please enter a c,p,t,or g: ";
}
switch (ch) {
case'c':cout