首页 > 解决方案 > C++ 接受带有“-”符号的命令行参数

问题描述

我是 C++ 新手,并试图读取如下指定的命令行参数。

./helloworld -i input_file -o outputfile -s flag3 -t flag4

我尝试按索引对标志进行硬编码,如下所示

int main(int argc, char *argv[]) {
 // argv[1] corresponds to -i
 // argv[2] corresponds to input_file
 // argv[3] corresponds to -o
 // argv[4] corresponds to outputfile
 // argv[5] corresponds to -s
 // argv[6] corresponds to flag3
 // argv[7] corresponds to -t
 // argv[8] corresponds to flag4

}

然后我意识到可以更改顺序,所以我不能使用硬编码索引,我使用 unordered_map<string, string>将 -i, -o, -s, -t 作为键和 inputfile, outputfile, flag3, flag4作为价值观。

这工作正常,但我想知道有没有更好的方法来做同样的事情。

标签: c++c++11command-line-arguments

解决方案


天啊。好的,您可以手动执行此操作,我将向您展示一些代码。但请查看 getopt()。它已经对你有很大帮助,但需要一点时间来适应。

但这里是你可以手动编码的方法:

int index = 1;
while (index < argc) {
    string cmnd = argv[index++];
    if (cmnd == "-i") {
        if (index >= argc) {
            usage();   // This should provide help on calling your program.
            exit(1);
        }
        inputFileName = argv[index++];
    }
    else if (cmnd == "-whatever") {
        // Continue to process all your other options the same way
    }
}

现在,这不是任何人这样做的方式。我们使用一些版本的 getopt()。我相信还有一个我喜欢的叫getopt_long。你会想挖这样的东西。然后我把我自己的包装包裹起来,这样我就可以做一些非常酷的事情。

如果您想查看我使用的包装器:https ://github.com/jplflyer/ShowLib.git并查看 OptionHandler.h 和 .cpp。它太酷了。我认为有一个如何在某处使用它的示例。

但是你需要知道它在底层是如何工作的,所以对于你的第一个程序,也许可以像我向你展示的那样手动完成。


推荐阅读