如果用户说他们想再玩一遍,如何重复程序?



我创建了一个请求鞋码的程序。如果鞋码是正确的,用户将收到一条消息:"您是正确的,您想再试一次吗?"他们可以回答是或不是。如果他们选择"不"程序会中断,他们会收到另一条消息,"感谢您的播放!">

如果用户输入yes作为答案而不是no,是否有一种方法可以强制程序返回while循环?

#include <iostream>
#include <string>
using namespace std;
int main()
{
int shoesize = 13;
int input;
string answer;
while (input != shoesize) {
cout << "Guess my shoe size!";
cin >> input;
if (input == shoesize) {
cout << "You are correct! Thanks for Playing! Would you like to play again? n";
cin >> answer;
if (answer == "no") {
cout << "Thank you for playing!";
}
}
}
return 0;
}

写一些"不断重复直到你想放弃"的东西的最好方法就是这样做:

while(true) {
.. do something ..
.. ask "do you want to quit" ..
if (answer == "yes") {
break;
}
}

程序员将立即识别出while(true){}& &;endless">循环,并查找break语句,顾名思义,该语句从"最内层循环,结束"无穷无尽"循环。这种设计的一个优点是,您可以根据需要在循环中的多个位置使用break语句。(在一个函数内,也可以return。)

这个怎么样

#include <iostream>
#include <string>
using namespace std;
int main()
{
int shoesize = 13;
string answer;
int input = 0;
while (input != shoesize && answer != "no") {
cout << "Guess my shoe size!";
cin >> input;
if (input == shoesize) {
cout << "You are correct! Thanks for Playing! Would you like to play again? n";
cin >> answer;
if (answer == "no") {
cout << "Thank you for playing!";
return 0;
}
}
}
}

相关内容

  • 没有找到相关文章