用户输入错误

Wrong User Input

本文关键字:错误 输入 用户      更新时间:2023-10-16

所以我正在使用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;
}
}

编辑:通过围绕if-else语句的简单while循环解决。

您不必在每个"如果"处都结束程序。 此外,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;
};

我希望这有所帮助。