从标准输入解析参数的最快方法
Fastest way to parse arguments from standard input
假设您从标准输入接收到的信息以以下方式格式化:
1 2 3 #3 John Tee #2
4 2 1 @1 Tree Bee #9
<int><int><int><char followed by int><string><string><char followed by int>
在程序中提取这些信息的最快方法是什么?另外,假设您想检查第4和第7个参数是否只包含一个'#'后面跟着一个数字(否则退出),或者您想检查一行是否提前结束,如:
1 4 2 #4 John
如何在c++中以最干净、最有效的方式做到这一点?
我最喜欢的基于行重复解析的方法是使用std::getline
作为while
循环的条件,然后解析其中的行:
std::string line;
while (std::getline(input_stream, line)) {
std::istringstream line_stream(line);
// Parse the line by extracting from line_stream
}
它确保在开始解析之前有一整行。这样,如果在对单行的解析中出现错误,它仍然会转到下一行继续。
例如,我会对以#
开头的字段执行检查,如下所示:
int value;
if (line_stream.get() == '#' &&
line_stream >> value &&
std::isspace(line_stream.peek())) {
// Success
}
我的方法是总是把我的提取放在某种条件下。这意味着您可以尽快发现格式的问题。
相关文章:
- c++方法参数只能在linux的发布模式下自行更改
- 使用移动语义:右值引用作为方法参数
- 无法将动态创建的对象数组从 qml 发送到 c++ 作为方法参数
- 将方法参数类型更改为子类中的派生类
- ofstream作为C 中的方法参数
- 使用 gmock 匹配器将 std::function 设置为 EXPECT_CALL 中的方法参数
- C com 方法参数扣除
- 获取非静态方法参数计数
- 使用 gmock 返回模拟方法参数
- 运行 QML 时出现"未知方法参数类型"错误
- 基本C - 构造contaning对象引用,并将其作为方法参数传递
- 将C 方法参数转换为模板参数会因编译错误而失败
- 如何在方法参数中使用boost :: asio :: buffer
- qsharedPointer作为方法参数或方法的返回值的良好实践
- 如何将方法指针声明为Typedef方法参数
- 方法参数中的 OpenCV 垫"预期")""
- 方法参数中的 consst* 常量
- 带有“class”详细类型说明符的方法参数
- 具有原始方法参数派生类的 C++ 重载方法参数
- C++ std::string length() 或 size() 不适用于方法参数