如何在显示游戏菜单时处理无效输入?

时间:2016-03-29 02:11:44

标签: c++ loops

#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;
}

如果用户没有输入有效答案,我该如何让他们重新启动问题?我必须使用循环吗?如果是这样,我该怎么做?

2 个答案:

答案 0 :(得分:0)

您可以添加以下条件:

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";
}  

}

答案 1 :(得分:0)

是的,您必须使用循环。类似的东西:

var _intensityTransformed = (_intensity * _volume._rescaleSlope + _volume._rescaleIntercept);

一旦你的答案有效,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"; } } 关键字就会退出循环,否则就会继续。