C ++接受带有“-”符号的命令行参数

C++ accepting command line argument with "-" symbol

我是 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 将 -i、-o、-s、-t 作为键,将 inputfile、outputfile、flag3、flag4 作为值。

这工作正常,但我想知道是否有更好的方法来做到这一点。

天哪。好的,您可以手动执行此操作,我将向您展示一些代码。但是请看一下 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。它太酷了。我认为有一个如何在某处使用它的示例。

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

您可以使用 3rdparty 库来解析命令行参数。
例如:https://github.com/mirror/tclap