从标准输入解析参数的最快方法

Fastest way to parse arguments from standard input

本文关键字:方法 参数 标准输入      更新时间:2023-10-16

假设您从标准输入接收到的信息以以下方式格式化:

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
}

我的方法是总是把我的提取放在某种条件下。这意味着您可以尽快发现格式的问题。