如果程序被指定像这样运行,那么在c++中解析命令行参数的最佳方式是什么:

prog [-abc] [input [output]]

是否有某种方法可以在标准库中实现这一点,或者我需要自己编写代码?


相关:

在unicode c++应用程序中解析命令行参数


当前回答

我喜欢C的getopt(),但是我老了。: -)

其他回答

提振。Program_options

Following from my comment and from rbaleksandar's answer, the arguments passed to any program in C are string values. You are provided the argument count (argc) which gives you the argument indexes zero-based beginning with the name of the program currently being run (which is always argv[0]). That leaves all arguments between 1 - argc as the user supplied arguments for your program. Each will be a string that is contained in the argument vector (which is a pointer to an array of strings you will seen written as char *argv[], or equivalently as a function parameter char **argv) Each of the strings argv[1] to argv[argc-1] are available to you, you simply need to test which argument is which.

这将允许您分离,并使它们可用为命令(cmd),选项(opt)和最后的参数(arg)到您的cmd。

Now it is worth noting, that the rules of your shell (bash, etc..) apply to the arguments passed to your program, word-splitting, pathname and variable expansion apply before your code gets the arguments. So you must consider whether single or more commongly double-quoting will be required around any of your arguments to prevent the normal shell splitting that would otherwise apply (e.g. ls -al my file.txt would results in 4 user-supplied arguments to your code, while ls -al "my file.txt" or ls -al my\ file.txt which would result in the 3 your were expecting.

把所有这些放在一起,您的简短解析可以像下面这样完成。(你也可以自由地做你喜欢的,使用一个开关而不是嵌套的if等…)

#include <stdio.h>

int main (int argc, char **argv) {

    char *cmd = NULL,   /* here, since you are using the arguments  */
         *opt = NULL,   /* themselves, you can simply use a pointer */
         *arg = NULL;   /* or the argument itself without a copy    */

    /* looping using the acutal argument index & vector */
    for (int i = 1; i < argc; i++) {
        if (*argv[i] != '-') {      /* checking if the 1st char is - */
            if (!cmd)               /* cmd is currently NULL, and    */
                cmd = argv[i];      /* no '-' it's going to be cmd   */
            else                    /* otherwise, cmd has value, so  */
                arg = argv[i];       /* the value will be opt        */
        }
        else                /* here the value has a leading '-', so  */
            opt = argv[i];  /* it will be the option */
    }

    printf ("\n cmd : %s\n opt : %s\n arg : %s\n\n",
            cmd, opt, arg);

    return 0;
}

使用/输出示例

如果你运行代码,你会发现它为参数提供了分离,并提供了单独的指针,以方便它们的使用:

$ ./bin/parse_cmd ls -la ./cs3000

 cmd : ls
 opt : -la
 arg : ./cs3000

(需要注意的是,如果你的任务是构建一个命令字符串,你需要复制多个值来表示opt或arg,那么你不能再简单地使用指针,而需要创建存储,要么通过简单的数组声明而不是指针开始,或者你可以根据需要动态分配存储,例如malloc, calloc和/或realloc。然后,您将有可用的存储空间来复制和连接其中的值。)

如果这是你的挑战,那么在所有这些答案之间,你应该知道如何处理你的问题。如果你必须更进一步,实际上让你的程序执行带有opt和arg的cmd,那么你会想要查看fork来生成一个半独立的进程,在其中运行将执行你的cmd opt和arg,使用类似于execv或execvp的东西。祝你好运,如果你有进一步的问题,请发表评论。

这是我最喜欢的执行命令行的方式,特别是,但绝对不是只有在效率是一个问题。这可能看起来有点过分,但我认为这种过分有一些缺点。

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

缺点:

您必须首先运行一个单独的工具来生成C/ c++哈希表的代码 不支持特定的命令行接口。例如,posix简写系统“-xyz”用一个破折号声明多个选项是很难实现的。

优点:

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

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

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

所以,在你的软件中有非常简洁干净的代码和一个自动生成的哈希表文件,你真的不需要手动更改。我怀疑boost::program_options即使没有效率作为优先级,实际上也能打败它。

我认为GNU GetOpt并不是马上就可以使用的。

Qt和Boost可能是一种解决方案,但您需要下载并编译大量代码。

所以我自己实现了一个解析器,它产生一个std::map<std::string, std::string>的参数。

例如,调用:

 ./myProgram -v -p 1234

地图将是:

 ["-v"][""]
 ["-p"]["1234"]

用法是:

int main(int argc, char *argv[]) {
    MainOptions mo(argc, argv);
    MainOptions::Option* opt = mo.getParamFromKey("-p");
    const string type = opt ? (*opt).second : "";
    cout << type << endl; /* Prints 1234 */
    /* Your check code */
}

MainOptions.h

#ifndef MAINOPTIONS_H_
#define MAINOPTIONS_H_

#include <map>
#include <string>

class MainOptions {
public:
    typedef std::pair<std::string, std::string> Option;
    MainOptions(int argc, char *argv[]);
    virtual ~MainOptions();
    std::string getAppName() const;
    bool hasKey(const std::string&) const;
    Option* getParamFromKey(const std::string&) const;
    void printOptions() const;
private:
    typedef std::map<std::string, std::string> Options;
    void parse();
    const char* const *begin() const;
    const char* const *end() const;
    const char* const *last() const;
    Options options_;
    int argc_;
    char** argv_;
    std::string appName_;
};

MainOptions.cpp

#include "MainOptions.h"

#include <iostream>

using namespace std;

MainOptions::MainOptions(int argc, char* argv[]) :
        argc_(argc),
        argv_(argv) {
    appName_ = argv_[0];
    this->parse();
}

MainOptions::~MainOptions() {
}

std::string MainOptions::getAppName() const {
    return appName_;
}

void MainOptions::parse() {
    typedef pair<string, string> Option;
    Option* option = new pair<string, string>();
    for (const char* const * i = this->begin() + 1; i != this->end(); i++) {
        const string p = *i;
        if (option->first == "" && p[0] == '-') {
            option->first = p;
            if (i == this->last()) {
                options_.insert(Option(option->first, option->second));
            }
            continue;
        } else if (option->first != "" && p[0] == '-') {
            option->second = "null"; /* or leave empty? */
            options_.insert(Option(option->first, option->second));
            option->first = p;
            option->second = "";
            if (i == this->last()) {
                options_.insert(Option(option->first, option->second));
            }
            continue;
        } else if (option->first != "") {
            option->second = p;
            options_.insert(Option(option->first, option->second));
            option->first = "";
            option->second = "";
            continue;
        }
    }
}

void MainOptions::printOptions() const {
    std::map<std::string, std::string>::const_iterator m = options_.begin();
    int i = 0;
    if (options_.empty()) {
        cout << "No parameters\n";
    }
    for (; m != options_.end(); m++, ++i) {
        cout << "Parameter [" << i << "] [" << (*m).first << " " << (*m).second
                << "]\n";
    }
}

const char* const *MainOptions::begin() const {
    return argv_;
}

const char* const *MainOptions::end() const {
    return argv_ + argc_;
}

const char* const *MainOptions::last() const {
    return argv_ + argc_ - 1;
}

bool MainOptions::hasKey(const std::string& key) const {
    return options_.find(key) != options_.end();
}

MainOptions::Option* MainOptions::getParamFromKey(
        const std::string& key) const {
    const Options::const_iterator i = options_.find(key);
    MainOptions::Option* o = 0;
    if (i != options_.end()) {
        o = new MainOptions::Option((*i).first, (*i).second);
    }
    return o;
}

Argstream与boost非常相似。Program_option:它允许将变量绑定到选项等。但是,它不处理存储在配置文件中的选项。