【发布时间】:2014-09-16 15:57:03
【问题描述】:
如何正确使用 do、while 或 for 循环来防止用户输入答案“1”或“2”以外的任何其他内容?
如果他们不这样做,程序应该告诉他们他们不能这样做,然后让他们回到上一个问题。
#include <iostream>
#include "Options.h"
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
cout << "\tWelcome to my text adventure game\n" << endl;
cout << "Please enter your characters Name: ";
string name;
cin >> name;
cout << "\nWelcome " << name << endl;
cout << "\nPlease choose the side you would like to play in - ";
Options OptionsObject;
OptionsObject.optionsSide();
string answer;
while(answer != "quit") {
cin >> answer;
cout << answer << endl;
}
if ( answer == "1" ) {
cout << "You chose the good side. Let the game begin\n " << endl;
cout << "You are located in a city named after the warrior who saved it from the evil\nmany years ago. The city of Redshore. " << endl;
cout << "You are no ordinary man in the City of Redshore. You are the king who rules it\nYou are seen as King of Justice, a good king.\nOne who only want what is best for his people" << endl;
cout << "but also a troubled man. You experienced something traumatizing when you\nwere a just a little boy, but no one knows about it,\nno one but yourself that is " << endl;
} else if( answer == "2" ) {
cout << "hey there" << endl;
}
}
【问题讨论】:
-
我看不到 goto,所以我无法提供替代方案。
-
is-goto-faster-than-while-and-for 可能值得一读并提供一些见解