windows 在 C++ 中从命令行处理参数的最有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/441547/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 11:49:14  来源:igfitidea点击:

Most efficient way to process arguments from the command-line in C++

c++windows

提问by Aaron

Suggestions for command-line argumentprocessing in C++ efficiently:

在 C++ 中有效处理命令行参数的建议:

Note: Windows specific only

注意:仅适用于 Windows

 1:     #include <iostream.h>
 2:     int main(int argc, char **argv)

Instead of, for example:

而不是,例如:

 if ( argc != 3 )  {
      ....
 }

Regards

问候

回答by j_random_hacker

If you just want to process command line options yourself, the easiestway is to put:

如果您只想自己处理命令行选项,最简单的方法是:

vector<string> args(argv + 1, argv + argc);

at the top of your main(). This copies all command-line arguments into a vector of std::strings. Then you can use ==to compare strings easily, instead of endless strcmp()calls. For example:

在您的main(). 这会将所有命令行参数复制到std::strings向量中。然后您可以==轻松地使用比较字符串,而不是无休止的strcmp()调用。例如:

int main(int argc, char **argv) {
    vector<string> args(argv + 1, argv + argc);
    string infname, outfname;

    // Loop over command-line args
    // (Actually I usually use an ordinary integer loop variable and compare
    // args[i] instead of *i -- don't tell anyone! ;)
    for (auto i = args.begin(); i != args.end(); ++i) {
        if (*i == "-h" || *i == "--help") {
            cout << "Syntax: foomatic -i <infile> -o <outfile>" << endl;
            return 0;
        } else if (*i == "-i") {
            infname = *++i;
        } else if (*i == "-o") {
            outfname = *++i;
        }
    }
}

[EDIT: I realised I was copying argv[0], the name of the program, into args-- fixed.]

[编辑:我意识到我正在将argv[0]程序名称复制到args-- 固定。]

回答by Ferruccio

With C++, the answer is usually in Boost...

对于 C++,答案通常在 Boost ...

Boost.Program Options

Boost.Program 选项

回答by Aaron Maenpaa

I'd suggest using a library. There's the classic and venerable getoptand I'm sure others.

我建议使用图书馆。有经典而古老的getopt,我相信还有其他人。

回答by brofield

There are a number of good libraries available.

有许多好的库可用。

Boost Program Optionsis a fairly heavyweight solution, both because adding it to your project requires you to build boost, and the syntax is somewhat confusing (in my opinion). However, it can do pretty much everything including having the command line options override those set in configuration files.

Boost Program Options是一个相当重量级的解决方案,因为将它添加到您的项目中需要您构建 boost,而且语法有些混乱(在我看来)。但是,它几乎可以做任何事情,包括让命令行选项覆盖配置文件中设置的选项。

SimpleOptis a fairly comprehensive but simple command line processor. It is a single file and has a simple structure, but only handles the parsing of the command line into options, you have to do all of the type and range checking. It is good for both Windows and Unix and comes with a version of glob for Windows too.

SimpleOpt是一个相当全面但简单的命令行处理器。它是一个单一的文件,结构简单,但只处理命令行解析成选项,你必须做所有的类型和范围检查。它对 Windows 和 Unix 都有好处,并且还带有一个适用于 Windows 的 glob 版本。

getopt is available on Windows. It is the same as on Unix machines, but it is often a GPL library.

getopt 在 Windows 上可用。它与 Unix 机器上的相同,但它通常是一个 GPL 库。

回答by brofield

This is my favourite way of doing the command line, especially, but definitely not only when efficiency is an issue. It might seem overkill, but I think there are few disadvantages to this overkill.

这是我最喜欢的命令行方式,尤其是,但绝对不仅仅是在效率成为问题的情况下。这似乎有点矫枉过正,但我​​认为这种矫枉过正几乎没有什么缺点。

Use gperf for efficient C/C++ command line processing

使用 gperf 进行高效的 C/C++ 命令行处理

Disadvantages:

缺点:

  • You have to run a separate tool first to generate the code for a hash table in C/C++
  • No support for specific command line interfaces. For example the posix shorthand system "-xyz" declaring multiple options with one dash would be hard to implement.
  • 你必须先运行一个单独的工具来为 C/C++ 中的哈希表生成代码
  • 不支持特定的命令行界面。例如,posix 速记系统“-xyz”用一个破折号声明多个选项将很难实现。

Advantages:

好处:

  • Your command line options are stored separately from your C++ code (in a separate configuration file, which doesn't need to be read at runtime, only at compile time).
  • All you have in your code is exactly one switch (switching on enum values) to figure out which option you have
  • Efficiency is O(n) where n is the number of options on the command line and the number of possible options is irrelevant. The slowest part is possibly the implementation of the switch (sometimes compilers tend to implement them as if else blocks, reducing their efficiency, albeit this is unlikely if you choose contiguous values, see: this article on switch efficiency)
  • The memory allocated to store the keywords is precisely large enough for the keyword set and no larger.
  • Also works in C
  • 您的命令行选项与您的 C++ 代码分开存储(在一个单独的配置文件中,不需要在运行时读取,只在编译时)。
  • 您在代码中所拥有的只是一个开关(打开枚举值)来确定您拥有哪个选项
  • 效率为 O(n),其中 n 是命令行上的选项数,可能的选项数无关紧要。最慢的部分可能是 switch 的实现(有时编译器倾向于将它们实现为 if else 块,从而降低了它们的效率,尽管如果您选择连续值,这不太可能,请参阅:这篇关于 switch 效率的文章
  • 分配给存储关键字的内存正好足够容纳关键字集,但不能更大。
  • 也适用于 C

Using an IDE like eclipse you can probably automate the process of running gperf, so the only thing you would have to do is add an option to the config file and to your switch statement and press build...

使用像 Eclipse 这样的 IDE,您可能可以自动化运行 gperf 的过程,因此您唯一需要做的就是在配置文件和 switch 语句中添加一个选项,然后按 build...

I used a batch file to run gperf and do some cleanup and add include guards with sed (on the gperf generated .hpp file)...

我使用了一个批处理文件来运行 gperf 并进行一些清理并使用 sed 添加包含保护(在 gperf 生成的 .hpp 文件上)...

So, extremely concise and clean code within your software and one auto-generated hash table file that you don't really need to change manually. I doubt if boost::program_options actually would beat that even without efficiency as a priority.

因此,您的软件中的代码非常简洁干净,并且是一个自动生成的哈希表文件,您实际上不需要手动更改。我怀疑 boost::program_options 是否真的会击败它,即使没有将效率作为优先事项。

回答by Denis Shevchenko

Try CLPP library. It's simple and flexible library for command line parameters parsing. Header-only and cross-platform. Uses ISO C++ and Boost C++ libraries only. IMHO it is easier than Boost.Program_options.

试试 CLPP 库。它是用于命令行参数解析的简单灵活的库。仅标题和跨平台。仅使用 ISO C++ 和 Boost C++ 库。恕我直言,它比 Boost.Program_options 更容易。

Library: http://sourceforge.net/projects/clp-parser

库:http: //sourceforge.net/projects/clp-parser

26 October 2010 - new release 2.0rc. Many bugs fixed, full refactoring of the source code, documentation, examples and comments have been corrected.

2010 年 10 月 26 日 - 新版本 2.0rc。修复了许多错误,更正了源代码、文档、示例和注释的完整重构。

回答by Stefan

If you don't want to use boost, I'd recommend thislittle helper class.

如果您不想使用 boost,我会推荐这个小助手类。