C++ 捕获分裂的人为错误
C++ Catching split human errors
我想做一个类似"CMD"的东西。我的意思是用户可以在控制台中输入他们的命令。我遇到的问题是每个命令都有效,但是例如,如果我们不编写每个参数,prog 就会崩溃。这是一小段代码:
void commande(std::string commandeWanted)
{
std::vector<std::string> fields;
boost::split(fields, commandeWanted, boost::is_any_of("|")); // I chose | as spliter
boost::to_upper(fields[0]);
//std::cout<< fields[1] << fields[2] <<std::endl;
if (fields[0] == "STOP")
stop(fields[1]);
else if (fields[0] == "DISCONNECT")
disconnect();
else if (fields[0] == "CONNECT")
connect();
else if (fields[0] == "SEND")
send(fields[1], fields[2]);
else if (fields[0] == "clean")
cleanConsole();
else if (fields[0] == "HELP")
displayHelp();
else
std::cout << "No command recognized." << std::endl;
}
知道吗?有什么建议吗?我尝试通过声明字段[1]和字段[2],但没有办法。问题是我可以输入"帮助"这将运行函数displayHelp,但例如,如果我写"发送"而不是"发送|谁|什么",这将使程序崩溃。提前谢谢你。
在访问fields[1]
之前检查fields.size() >= 2
,依此类推fields[2]
。
如果你规范化所有函数的样子,你可以避免大量的逻辑重复和参数大小检查:
struct Command {
size_t numArgs;
std::function<void(std::vector<std::string>)> fun;
};
std::map<std::string, Command> commands = {
{"STOP", {1, stop}},
{"DISCONNECT", {0, disconnect}},
{"SEND", {2, send}},
// ...
};
// after you split
boost::to_upper(fields[0]);
auto it = commands.find(fields[0]);
if (it != commands.end()) {
// pop the first one
fields.erase(fields.begin());
// check the size
if (fields.size() != it->second.numArgs) {
// error: wrong number of args
}
else {
// ok, call me
it->second.fun(fields);
}
}
else {
// command not found
}
不幸的是,C++ python *
运算符没有很好的等价物来解压缩向量 - 但这样至少你知道你在所有正确的位置都有所有正确的参数,即使你所有的函数现在都采用一个向量。
您需要在代码中添加检查,以确保在访问它们之前存在足够的字段。
(看起来您在split
通话中切换了fields
和champs
。
像这样:
void commande(std::string commandeWanted)
{
std::vector<std::string> fields;
boost::split(fields, commandeWanted, boost::is_any_of("|")); // I chose | as spliter
boost::to_upper(fields[0]);
//std::cout<< fields[1] << fields[2] <<std::endl;
if (fields[0] == "STOP"){
if(fields.size >=2)stop(fields[1]);
}
else if (fields[0] == "DISCONNECT")
disconnect();
else if (fields[0] == "CONNECT")
connect();
else if (fields[0] == "SEND"){
if(fields.size() >= 3)(fields[1], fields[2]);
}
else if (fields[0] == "clean")
cleanConsole();
else if (fields[0] == "HELP")
displayHelp();
else
std::cout << "No command recognized." << std::endl;
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- C++ 捕获分裂的人为错误