用户输入错误
Wrong User 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;
}
}
编辑:通过围绕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;
};
我希望这有所帮助。
相关文章:
- 通过错误处理,在C++中可靠地获得用户十六进制输入
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- 堆栈中大小变量输入错误 (C++)
- 实现 DFS 在较短的输入下工作正常,但在较大的输入下会抛出分段错误
- C++中的输入限制和错误检查
- 关于 SIGTSTP 错误和无休止的输入
- 为什么不能通过在错误输入后设置 std::cin.clear() 来使用 std::cin?
- 这段代码在获得错误输入时不会阻止 stoi 运行
- 无法转换 .CATPart 文件.错误:输入文件路径似乎包含不支持的字符
- 使用 cin 错误输入多个浮点数
- 构造函数错误:输入末尾的预期“{”
- 如何一次一个单词而不是一行一行地消除错误输入
- 错误输入未在此范围中显示
- c++在没有tryCatch块的情况下捕获错误输入
- c++中的纠错循环,查找字符串中的特定字符并将其标记为错误输入
- 如何为错误输入编写异常处理
- Swig错误-错误:输入(2)中的语法错误
- 错误:输入末尾应为“}”
- std::cin无限循环错误输入
- 如何避免来自用户的错误输入?