![]() |
#2
Lyone2010-12-09 13:56
|

#include <iostream>
#include <string>
int main()
{
using std::cout;
using std::cin;
using std::endl;
using std::string;
string str_c = "carnivore";
string str_p = "pianist";
string str_t = "tree";
string str_g = "game";
string str_prefix = "A maple is a ";
string str_reInputInfo = "Please enter a c, p, t, or g: ";
char ch;
bool bool_hasInput = false;
cout << "Please enter one of the following choices:" << endl;
cout << "c) " << str_c << "\t\t\t"
<< "p) " << str_p << "\n"
<< "t) " << str_t << "\t\t\t\t"
<< "g) " << str_g << "\n";
do
{
while (cin >> ch)
{
switch(ch)
{
case 'c':cout << str_prefix + str_c + '.'; goto label;
case 'p':cout << str_prefix + str_p + '.'; goto label;
case 't':cout << str_prefix + str_t + '.'; goto label;
case 'g':cout << str_prefix + str_g + '.'; goto label;
}
cout << str_reInputInfo;
}
cin.clear();
}while(1);
label:
return 0;
}
问题:(1)能否修改程序让程序不使用goto语句?#include <string>
int main()
{
using std::cout;
using std::cin;
using std::endl;
using std::string;
string str_c = "carnivore";
string str_p = "pianist";
string str_t = "tree";
string str_g = "game";
string str_prefix = "A maple is a ";
string str_reInputInfo = "Please enter a c, p, t, or g: ";
char ch;
bool bool_hasInput = false;
cout << "Please enter one of the following choices:" << endl;
cout << "c) " << str_c << "\t\t\t"
<< "p) " << str_p << "\n"
<< "t) " << str_t << "\t\t\t\t"
<< "g) " << str_g << "\n";
do
{
while (cin >> ch)
{
switch(ch)
{
case 'c':cout << str_prefix + str_c + '.'; goto label;
case 'p':cout << str_prefix + str_p + '.'; goto label;
case 't':cout << str_prefix + str_t + '.'; goto label;
case 'g':cout << str_prefix + str_g + '.'; goto label;
}
cout << str_reInputInfo;
}
cin.clear();
}while(1);
label:
return 0;
}
(2)这个程序可以避免全部的数字、符号、无效字母和多数像ctrl+C这样的输入,可不能避免ctrl+Z的输入,当输入ctrl+Z后不能按预期的那样提示信息。如何修改程序?