接受标准输入或 CLI 参数的设计模式

Design pattern for accepting stdin OR CLI arguments

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

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

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]);
        }
    }
}

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

我对设计模式/示例实现很感兴趣。请随意参考执行此操作的库(Boost?),但请 share/explain 一个示例实现。

通常你只会从 stdin 中读取 input,而不是 arguments/options。通过读取和评估 arguments/options,程序应该决定它是否期望来自标准输入或例​​如文件参数。

来自 manpage of grep 的示例:

Synopsis

grep [OPTIONS] PATTERN [FILE...]

Description

grep searches the named input FILEs (or standard input if no files are named, or if a single hyphen-minus (-) is given as file name) for lines containing a match to the given 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 -

对于解析 options/arguments boost 具有 program options library