如果你只是想爲了讓你已經用少一點的代碼做同樣的事情,這將會起作用。
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"));
來源
2013-04-24 01:47:38
jxh
我會避免使用單詞'continue'一個變量名,因爲它是在類似C語言的關鍵字。 '重試'會更好。 – Patashu 2013-04-24 00:49:26
這是什麼語言?有可能會有語言結構解開這個問題。我沒有看到它是如何被「無法使用」的。您可以移動代碼,也許使用布爾邏輯而不是if/then,但這實際上是一個編碼器偏好,並且可能不會在您的代碼中受支持。即如果你的語言支持它,你可以在主循環之外加一個continue =(answer!=「n」);但是我不知道你會同意它更簡單。我認爲這是我自己。 – 2013-04-24 01:13:00
這裏的許多答案似乎認爲你想要做很多次的事情。你的代碼只想做一件事,但想要與用戶覈對,直到他們輸入正確的迴應。 – 2013-04-24 07:57:00