解析C+中的命令行参数+;? P> C++中命令行参数解析的最佳方法是:如果程序被指定为这样运行: prog [-abc] [input [output]] std::vector<std::string> args(argv, argv+argc); for (size_t i = 1; i < args.size(); ++i) { if (args[i] == "x") { // Handle x } else if (args[i] == "y") { // Handle y } // ... }
在标准库中是否有这样做的方法,或者我是否需要编写自己的代码解析C+中的命令行参数+;? P> C++中命令行参数解析的最佳方法是:如果程序被指定为这样运行: prog [-abc] [input [output]] std::vector<std::string> args(argv, argv+argc); for (size_t i = 1; i < args.size(); ++i) { if (args[i] == "x") { // Handle x } else if (args[i] == "y") { // Handle y } // ... },c++,command-line-arguments,C++,Command Line Arguments,在标准库中是否有这样做的方法,或者我是否需要编写自己的代码 相关的: GNU 使用GetOpt的一个简单示例: // C/C++ Libraries: #include <string> #include <iostream> #include <unistd.h> // Namespaces: using namespace std; int main(int argc, char** argv) { int opt; bool f
相关的:
- GNU
使用GetOpt的一个简单示例:
// C/C++ Libraries:
#include <string>
#include <iostream>
#include <unistd.h>
// Namespaces:
using namespace std;
int main(int argc, char** argv) {
int opt;
bool flagA = false;
bool flagB = false;
// Shut GetOpt error messages down (return '?'):
opterr = 0;
// Retrieve the options:
while ( (opt = getopt(argc, argv, "ab")) != -1 ) { // for each option...
switch ( opt ) {
case 'a':
flagA = true;
break;
case 'b':
flagB = true;
break;
case '?': // unknown option...
cerr << "Unknown option: '" << char(optopt) << "'!" << endl;
break;
}
}
// Debug:
cout << "flagA = " << flagA << endl;
cout << "flagB = " << flagB << endl;
return 0;
}
//C/C++库:
#包括
#包括
#包括
//名称空间:
使用名称空间std;
int main(int argc,字符**argv){
int-opt;
bool-flagA=false;
bool-flagB=false;
//关闭GetOpt错误消息(返回“?”):
opterr=0;
//检索选项:
而((opt=getopt(argc,argv,“ab”))!=-1){//对于每个选项。。。
开关(opt){
案例“a”:
flagA=真;
打破
案例“b”:
flagB=true;
打破
案例“?”://未知选项。。。
cerrGNUC库中有一些工具,包括
如果您使用的是Qt,并且喜欢GetOpt接口,那么它发布了一个很好的接口。与boost.program\u option非常类似:它允许将变量绑定到选项等。但是它不处理存储在配置文件中的选项。并且有一个可用的接口
<命令>解析:“命令行解析”,只需选择一个。 <>用C++,答案通常在Boost…
我建议使用一个库。有经典的、古老的,我相信还有其他的。如果您只想自己处理命令行选项,最简单的方法是:
vector<string> args(argv + 1, argv + argc);
[编辑:我意识到我正在将程序名argv[0]
复制到args
--修复。]有很多好的库可用
是一个相当重的解决方案,因为将它添加到项目中需要构建boost,而且语法有点混乱(在我看来)。但是,它几乎可以做任何事情,包括让命令行选项覆盖配置文件中设置的选项
是一个相当全面但简单的命令行处理器。它是一个文件,结构简单,但只处理将命令行解析为选项的过程,您必须执行所有类型和范围检查。它适用于Windows和Unix,并且还附带了一个版本的glob for Windows
GETopt在Windows上可用。它与UNIX机器相同,但它通常是GPL库。
应该做的技巧
< P>可以使用(LGPL)或各种C++端口之一,如(GPL)。
下面是一个使用GetOpt获取所需内容(prog[-ab]输入)的简单示例:
// C Libraries:
#include <string>
#include <iostream>
#include <unistd.h>
// Namespaces:
using namespace std;
int main(int argc, char** argv) {
int opt;
string input = "";
bool flagA = false;
bool flagB = false;
// Retrieve the (non-option) argument:
if ( (argc <= 1) || (argv[argc-1] == NULL) || (argv[argc-1][0] == '-') ) { // there is NO input...
cerr << "No argument provided!" << endl;
//return 1;
}
else { // there is an input...
input = argv[argc-1];
}
// Debug:
cout << "input = " << input << endl;
// Shut GetOpt error messages down (return '?'):
opterr = 0;
// Retrieve the options:
while ( (opt = getopt(argc, argv, "ab")) != -1 ) { // for each option...
switch ( opt ) {
case 'a':
flagA = true;
break;
case 'b':
flagB = true;
break;
case '?': // unknown option...
cerr << "Unknown option: '" << char(optopt) << "'!" << endl;
break;
}
}
// Debug:
cout << "flagA = " << flagA << endl;
cout << "flagB = " << flagB << endl;
return 0;
}
//C库:
#包括
#包括
#包括
//名称空间:
使用名称空间std;
int main(int argc,字符**argv){
int-opt;
字符串输入=”;
bool-flagA=false;
bool-flagB=false;
//检索(非选项)参数:
如果((argc如果可以使用boost库,我建议使用boost::program\u选项
STL和常规的C++/C运行库中都没有任何特定的内容。对于boost::program_options
和GNU getopt的建议都很好
但是,对于简单的命令行选项,我倾向于使用std::find
例如,在命令行参数-f
后读取文件名。您还可以检测是否传入了单个单词选项,如-h
,以获取帮助
#include <algorithm>
char* getCmdOption(char ** begin, char ** end, const std::string & option)
{
char ** itr = std::find(begin, end, option);
if (itr != end && ++itr != end)
{
return *itr;
}
return 0;
}
bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
return std::find(begin, end, option) != end;
}
int main(int argc, char * argv[])
{
if(cmdOptionExists(argv, argv+argc, "-h"))
{
// Do stuff
}
char * filename = getCmdOption(argv, argv + argc, "-f");
if (filename)
{
// Do interesting things
// ...
}
return 0;
}
#包括
char*getCmdOption(char**begin,char**end,const std::string和option)
{
char**itr=std::find(开始、结束、选项);
如果(itr!=结束&&++itr!=结束)
{
返回*itr;
}
返回0;
}
bool cmdOptionExists(字符**开始,字符**结束,常量std::字符串和选项)
{
返回std::find(开始、结束、选项)!=end;
}
int main(int argc,char*argv[])
{
if(cmdOptionExists(argv,argv+argc,“-h”))
{
//做事
}
char*filename=getCmdOption(argv,argv+argc,“-f”);
如果(文件名)
{
//做有趣的事
// ...
}
返回0;
}
在使用这种方法时,必须使用std::strings作为std::find的值,否则将对指针值执行相等性检查
我希望可以编辑此响应,而不是添加一个新响应,因为这是基于原始答案的。我稍微重新编写了函数,并将它们封装在一个类中,因此下面是代码。我认为以这种方式使用它可能也是可行的:
class InputParser{
public:
InputParser (int &argc, char **argv){
for (int i=1; i < argc; ++i)
this->tokens.push_back(std::string(argv[i]));
}
/// @author iain
const std::string& getCmdOption(const std::string &option) const{
std::vector<std::string>::const_iterator itr;
itr = std::find(this->tokens.begin(), this->tokens.end(), option);
if (itr != this->tokens.end() && ++itr != this->tokens.end()){
return *itr;
}
static const std::string empty_string("");
return empty_string;
}
/// @author iain
bool cmdOptionExists(const std::string &option) const{
return std::find(this->tokens.begin(), this->tokens.end(), option)
!= this->tokens.end();
}
private:
std::vector <std::string> tokens;
};
int main(int argc, char **argv){
InputParser input(argc, argv);
if(input.cmdOptionExists("-h")){
// Do stuff
}
const std::string &filename = input.getCmdOption("-f");
if (!filename.empty()){
// Do interesting things ...
}
return 0;
}
类输入解析器{
公众:
InputParser(int&argc,字符**argv){
对于(int i=1;itokens.push_back(std::string(argv[i]);
}
///@作者伊恩
const std::string和getCmdOption(const std::string和option)const{
std::vector::const_迭代器itr;
itr=std::find(this->tokens.begin(),this->tokens.end(),选项);
如果(itr!=此->令牌.end()&&++itr!=此->令牌.end()){
返回*itr;
}
静态常量std::字符串空字符串(“”);
返回空字符串;
}
///@作者伊恩
bool cmdOptionExists(const std::string&option)const{
return std::find(this->tokens.begin(),this->tokens.end(),选项)
!=this->tokens.end();
}
私人:
std::向量标记;
};
int main(int argc,字符**argv){
InputParser输入(argc、argv);
if(input.cmdOptionExists(“-h”)){
//做事
}
const std::string&filename=input.getCmdOption(“-f”);
如果(!filename.empty()){
//做有趣的事情。。。
}
返回0;
}
试试。它允许您读取和解析命令行以及配置文件。我喜欢C的getopt(),但后来我老了。:-谷歌的试试CLPP库。它既简单又实用
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i],"-i")==0) {
filename = argv[i+1];
printf("filename: %s",filename);
} else if (strcmp(argv[i],"-c")==0) {
convergence = atoi(argv[i + 1]);
printf("\nconvergence: %d",convergence);
} else if (strcmp(argv[i],"-a")==0) {
accuracy = atoi(argv[i + 1]);
printf("\naccuracy:%d",accuracy);
} else if (strcmp(argv[i],"-t")==0) {
targetBitRate = atof(argv[i + 1]);
printf("\ntargetBitRate:%f",targetBitRate);
} else if (strcmp(argv[i],"-f")==0) {
frameRate = atoi(argv[i + 1]);
printf("\nframeRate:%d",frameRate);
}
}
#include <string>
#include <iostream>
#include <algorithm>
#include <tclap/CmdLine.h>
int main(int argc, char** argv)
{
// Wrap everything in a try block. Do this every time,
// because exceptions will be thrown for problems.
try {
// Define the command line object, and insert a message
// that describes the program. The "Command description message"
// is printed last in the help text. The second argument is the
// delimiter (usually space) and the last one is the version number.
// The CmdLine object parses the argv array based on the Arg objects
// that it contains.
TCLAP::CmdLine cmd("Command description message", ' ', "0.9");
// Define a value argument and add it to the command line.
// A value arg defines a flag and a type of value that it expects,
// such as "-n Bishop".
TCLAP::ValueArg<std::string> nameArg("n","name","Name to print",true,"homer","string");
// Add the argument nameArg to the CmdLine object. The CmdLine object
// uses this Arg to parse the command line.
cmd.add( nameArg );
// Define a switch and add it to the command line.
// A switch arg is a boolean argument and only defines a flag that
// indicates true or false. In this example the SwitchArg adds itself
// to the CmdLine object as part of the constructor. This eliminates
// the need to call the cmd.add() method. All args have support in
// their constructors to add themselves directly to the CmdLine object.
// It doesn't matter which idiom you choose, they accomplish the same thing.
TCLAP::SwitchArg reverseSwitch("r","reverse","Print name backwards", cmd, false);
// Parse the argv array.
cmd.parse( argc, argv );
// Get the value parsed by each arg.
std::string name = nameArg.getValue();
bool reverseName = reverseSwitch.getValue();
// Do what you intend.
if ( reverseName )
{
std::reverse(name.begin(),name.end());
std::cout << "My name (spelled backwards) is: " << name << std::endl;
}
else
std::cout << "My name is: " << name << std::endl;
} catch (TCLAP::ArgException &e) // catch any exceptions
{ std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl; }
}
alias bar="foo --flag1 --flag2 --flag3"
bar --flag1=0
#include <QCoreApplication>
#include <QCommandLineParser>
#include <QDebug>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
app.setApplicationName("ToolX");
app.setApplicationVersion("1.2");
QCommandLineParser parser;
parser.setApplicationDescription("Tool for doing X.");
parser.addHelpOption();
parser.addVersionOption();
parser.addPositionalArgument("infile",
QCoreApplication::translate("main", "Input file."));
QCommandLineOption verbose_opt("+",
QCoreApplication::translate("main", "be verbose"));
parser.addOption(verbose_opt);
QCommandLineOption out_opt(QStringList() << "o" << "output",
QCoreApplication::translate("main", "Output file."),
QCoreApplication::translate("main", "filename"), // value name
QCoreApplication::translate("main", "out") // default value
);
parser.addOption(out_opt);
// exits on error
parser.process(app);
const QStringList args = parser.positionalArguments();
qDebug() << "Input files: " << args
<< ", verbose: " << parser.isSet(verbose_opt)
<< ", output: " << parser.value(out_opt)
<< '\n';
return 0;
}
$ ./qtopt -h
Usage: ./qtopt [options] infile
Tool for doing X.
Options:
-h, --help Displays this help.
-v, --version Displays version information.
-+ be verbose
-o, --output Output file.
Arguments:
infile Input file.
$ ./qtopt -v
ToolX 1.2
$ ./qtopt b1 -+ -o tmp blah.foo
Input files: ("b1", "blah.foo") , verbose: true , output: "tmp"
$ ./qtopt
Input files: () , verbose: false , output: "out"
$ ./qtopt --hlp
Unknown option 'hlp'.
$ echo $?
1
./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 */
}
#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_;
};
#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;
}
ls
user@computer:~$ ls
Documents Pictures Videos ...
user@computer:~$ ls Picture
image1.jpg image2.jpg ...
user@computer:~$ ls Pictures
-rw-r--r-- 1 user user 215867 Oct 12 2014 image1.jpg
-rw-r--r-- 1 user user 268800 Jul 31 2014 image2.jpg
...
user@computer:~$ ls -l -h Pictures
-rw-r--r-- 1 user user 211K Oct 12 2014 image1.jpg
-rw-r--r-- 1 user user 263K Jul 31 2014 image2.jpg
...
int main (int argc, char *argv[]) { // When you launch your application the first line of code that is ran is this one - entry point
// Some code here
return 0; // Exit code of the application - exit point
}
#include <iostream>
using std::cout;
using std::endl;
int main (int argc, char *argv[]) {
cout << "Arguments' count=%d" << argc << endl;
// First argument is ALWAYS the command itself
cout << "Command: " << argv[0] << endl;
// For additional arguments we start from argv[1] and continue (if any)
for (int i = 1; i < argc; i++) {
cout << "arg[" << i << "]: " << argv[i] << endl;
}
cout << endl;
return 0;
}
user@computer:~$ ls -y
ls: invalid option -- 'y'
Try 'ls --help' for more information.
* `if (strcmp(argv[1], "x") == 0) { ... }` - compare the pointer value
* `if (std::string(argv[1]) == "x") { ... }` - convert to string and then compare
std::vector<std::string> args(argv, argv+argc);
for (size_t i = 1; i < args.size(); ++i) {
if (args[i] == "x") {
// Handle x
}
else if (args[i] == "y") {
// Handle y
}
// ...
}
// No for loop!
if (args[1] == "x") {
// Handle x
}
else if (args[2] == "y") {
// Handle y
}
// ...
if (argc > 1 && argc <= 3) {
if (args[1] == "x") {
// Handle x
}
else if (args[2] == "y") {
// Handle y
}
}