错误的用户输入

时间:2017-07-22 23:06:22

标签: c++ input

所以我正在使用C ++进行纸牌游戏,而我正在做一些基本的用户输入,但我想知道如何处理错误的用户输入,这样你就可以在不终止程序的情况下重试,我就是这样做的。 ;我不知道该怎么做。

#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include <algorithm>
using namespace std;

int main()
{
    string command;
    int i = 0;
    char c;
    string test1 = "help";
    string test2 = "start";

    cout<< "Welcome to My Card Game" << "\n";
    cout<<"\n";
    cout<< "For Rules please type 'rules'" << "\n";
    cout<<"\n";
    cout<< "To Play please type 'start'" << "\n";
    getline(cin, command);
    transform(command.begin(), command.end(), command.begin(),::tolower);
    if(!command.compare(test1)){
        cout << "You typed help" << "\n";
        return 0;
    }
    if(!command.compare(test2)){
        cout << "You typed start" << "\n";
        return 0;
    }
    else{
        cout << "Not a valid command" << "\n";
        return 0;
}
}

编辑:解决了一个简单的while循环,包裹在if-else语句中。

1 个答案:

答案 0 :(得分:1)

你不一定要在每一个'if'结束程序。 也是'!'你的if语句中的运算符是不必要的,因为它检查不等式而不是相等。

您可以尝试循环程序,如果用户键入无效命令,将使其重新启动,在您的情况下:

#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
#include <algorithm>
using namespace std;

int main() {
    string command;
    int i = 0;
    char c;
    string test1 = "help";
    string test2 = "start";
    cout<< "Welcome to My Card Game" << "\n";
    cout<<"\n";
    cout<< "For Rules please type 'rules'" << "\n";
    cout<<"\n";
    cout<< "To Play please type 'start'" << "\n";
    while (1) {
        getline(cin, command);
        transform(command.begin(), command.end(), command.begin(), ::tolower);
        if(command.compare(test1)){
            cout << "You typed help" << "\n";
            //continue code for when they type help.
        }
        else if (command.compare(test2)) {
            cout << "You typed start" << "\n";
            //continue code for when they type start.
            //make sure that you break the while loop with 'break;' when they finish the game so that your program will end.
        }
        else {
            cout << "Not a valid command" << "\n";
        };
    };
    return 0;
};

我希望这会有所帮助。