如果你只是想用更少的代码让你已经拥有的东西做同样的事情,这将起作用。
string answer="y";
while (answer=="y") {
//do code
for(;;) {
cout << "Do you wish to continue" << endl;
getline(cin, answer);
if ((answer=="y")||(answer=="n")) break;
cout << "That wasnt \"y\" or \"n\" please type something again" << endl;
}
}
代码略少,但更模糊:
string answer="y";
while (answer!="n") {
if (answer=="y") {
//do code
} else {
cout << "That wasnt \"y\" or \"n\" please type something again" << endl;
}
cout << "Do you wish to continue" << endl;
getline(cin, answer);
}
这是一个<termios.h>
用来获得答案的版本。它使用更多代码,但表现得更“雄辩”。
int getch (void)
{
int c;
struct termios oldt;
struct termios newt;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~ICANON;
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
c = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
return c;
}
bool again (std::string prompt, std::string yes, std::string no)
{
bool doyes = false;
bool dono = false;
for (;;) {
std::cout << prompt;
int c = getch();
std::cout << std::endl;
doyes = (yes.find(c) != yes.npos);
dono = (no.find(c) != no.npos);
if (doyes || dono) break;
std::cout << "Type [" << yes << "] for yes, or [" << no << "] for no.";
std::cout << std::endl;
}
return doyes;
}
您可以按照其他人的建议使用它:
do {
// the interesting code
} while (again("Do you wish to continue? ", "y", "n"));