#include <iostream>
#include <string>
using namespace std;
int main() { //Program starts
cout << "-------------------------------" << endl;
cout << "Welcome to Ninjas vs. Samurais!" << endl; //The intro
cout << "-------------------------------" << endl;
string newAdventure;
string chosenKind;
cout << "Hello, new solder! Are you ready for your adventure to begin, yes or no?n"; //Asks you if you are ready
cin >> newAdventure;//Takes in if you are ready or not
if (newAdventure == "yes" || newAdventure == "Yes" || newAdventure == "Yes!") { //Asks if they are ready
cout << "Great!n" << endl;
}
else if (newAdventure == "no" || newAdventure == "No" || newAdventure == "No!") { //Asks if they are ready
cout << "Too bad!n" << endl;
}
else {
cout << "Please type a yes or no answer!n";
}
system("PAUSE");
return 0;
}
如果用户没有输入有效的答案,我该如何让他们重新开始提问?我必须使用循环吗?如果是这样,我将如何做?
是的,你必须使用循环。像这样:
while(cin >> newAdventure)//Takes in if you are ready or not
{
if (newAdventure == "yes" || newAdventure == "Yes" || newAdventure == "Yes!") { //Asks if they are ready
cout << "Great!n" << endl;
break;
}
else if (newAdventure == "no" || newAdventure == "No" || newAdventure == "No!") { //Asks if they are ready
cout << "Too bad!n" << endl;
break;
}
else {
cout << "Please type a yes or no answer!n";
}
}
一旦您的答案有效,break
关键字将退出循环,否则,它将继续运行。
您可以添加如下条件:
while(true)
{
cout << "Hello, new solder! Are you ready for your adventure to begin, yes or no?n"; //Asks you if you are ready
cin >> newAdventure;//Takes in if you are ready or not
if (newAdventure == "yes" || newAdventure == "Yes" || newAdventure == "Yes!") { //Asks if they are ready
cout << "Great!n" << endl;
break;
}
else if (newAdventure == "no" || newAdventure == "No" || newAdventure == "No!") { //Asks if they are ready
cout << "Too bad!n" << endl;
break;
}
else {
cout << "Please type a yes or no answer!n";
}
}