【问题标题】:Design pattern for accepting stdin OR CLI arguments接受标准输入或 CLI 参数的设计模式
【发布时间】:2018-03-03 09:38:35
【问题描述】:

对于 C++,我如何接受 CLI 参数标准输入?

例如,假设我有一个函数foo(),我想调用可变数量的参数。对于标准 args,我只是使用类似的东西:

int main(int argc, char* argv[]) {
    if (argc < 2) {
        std::cout << "usage goes here.\n";
    } else {
        for (int i; i < argc; ++i) {
            foo(argv[i]);
        }
    }
}

但是如果他们通过标准输入将它们发送给我并将参数通过管道传输到我的应用程序怎么办?有没有办法检测和接受/处理两者?在现代 C++(C++11 及更高版本)中执行此操作的有效设计模式是什么?

我对设计模式/示例实现感兴趣。请随意参考执行此操作的库(Boost?),但请分享/解释示例实现。

【问题讨论】:

    标签: c++ command-line-arguments stdin argv


    【解决方案1】:

    通常您只会从标准输入读取 input,而不是参数/选项。通过读取和评估参数/选项,程序应该决定它是否需要来自标准输入或例​​如输入。文件参数。

    例如来自manpage of grep:

    概要

    grep [选项] 模式 [文件...]

    说明

    grep 搜索命名的输入文件(或标准输入,如果 没有文件 被命名,或者如果单个 连字符减号 (-) 给出 作为文件名)包含与给定 PATTERN 匹配的行。

    缺少 FILE 参数或 - 选项指示 grep 读取标准输入。

    您的程序的调用可能如下所示,缺少文件参数表示从标准输入读取输入:

    # file argument, input is in the file
    command -o someoption filename
    
    # file content supplied via stdin
    command -o someoption < filename     
    
    # with pipe and - (stdin) as file argument
    othercommand | command -o someoption -
    

    对于解析选项/参数,boost 有 program options library

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 2011-02-07
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多