简体   繁体   English

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

[英]C++ accepting command line argument with "-" symbol

I am new to c++ and trying to read command line arguments specified as below.我是 c++ 的新手,并试图读取如下指定的命令行 arguments。

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

I tried hardcoding the flags by index as below我尝试按索引对标志进行硬编码,如下所示

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

}

Then i realized the order can be changed so I can't use hardcoded index, I used a unordered_map<string, string> to put the -i, -o, -s, -t as keys and inputfile, outputfile, flag3, flag4 as values.然后我意识到可以更改顺序,所以我不能使用硬编码索引,我使用unordered_map<string, string>将 -i, -o, -s, -t 作为键和 inputfile, outputfile, flag3, flag4作为价值观。

This is working fine, but I was wondering is there any better way to do the same.这工作正常,但我想知道有没有更好的方法来做同样的事情。

Oh my gosh.天啊。 Okay, you can do this manually, and I'll show you some code.好的,您可以手动执行此操作,我将向您展示一些代码。 But please look at getopt().但请查看 getopt()。 It already helps you out quite a bit, but it takes a little to get used to.它已经对你有很大帮助,但需要一点时间来适应。

But here's how you could code it manually:但这里是你可以手动编码的方法:

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
    }
}

Now, this isn't how anyone does this.现在,这不是任何人这样做的方式。 We use some version of getopt().我们使用一些版本的 getopt()。 There's another one I like called getopt_long, I believe.我相信还有一个我喜欢的叫getopt_long。 You'll want to dig something up like that.你会想挖这样的东西。 Then I put my own wrapper around all of that so I can do some really cool things.然后我把我自己的包装包裹起来,这样我就可以做一些非常酷的事情。

If you want to see the wrapper I use: https://github.com/jplflyer/ShowLib.git and look at the OptionHandler.h and.cpp.如果您想查看我使用的包装器: https://github.com/jplflyer/ShowLib.git并查看 OptionHandler.h 和.cpp。 It's pretty cool.它太酷了。 I think there's an example of how to use it somewhere.我认为有一个如何在某处使用它的示例。

But you need to know how it works under the hood, so for your first programs, maybe do it manually like I've shown you.但是你需要知道它在底层是如何工作的,所以对于你的第一个程序,也许可以像我向你展示的那样手动完成。

You can use a 3rdparty library to parsing commandline arguments.您可以使用 3rdparty 库来解析命令行 arguments。
For example: https://github.com/mirror/tclap例如: https://github.com/mirror/tclap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM