网上关于这方面的资料网上有很多,在这里给大家几个链接:
http://blog.csdn.net/wangxvfeng101/article/details/11979487
http://blog.chinaunix.net/uid-10275706-id-3702543.html
http://www.oschina.net/code/snippet_126720_5039
先粘贴我的练习代码:
****.exe 参数1 参数2 (1)
我们是直接将参数用空格分开,直接写在.exe后面就好了。
int main(int argc, char* argv[])
{
string image_path;
int num;
boost::program_options::options_description opts("Help Message");
opts.add_options()
("help,h", "A example is->sharpness_clean.exe image_path")
//("image_path,I", boost::program_options::value<string>(&image_path)->default_value("E:/wu_test/pictures1/000000000.jpg"), "图片的路径")
//("num,n", boost::program_options::value<int>(&num)->default_value(10), "测试用");
("image_path,I", boost::program_options::value<string>(&image_path), "图片的路径")
("num,n", boost::program_options::value<int>(&num), "测试用");
boost::program_options::variables_map vm;
try
{
boost::program_options::store(boost::program_options::parse_command_line(argc, argv, opts), vm);
}
catch (boost::program_options::error_with_no_option_name &ex)
{
cout << ex.what() << endl;
}
boost::program_options::notify(vm);
if (vm.count("help"))
{
cout << opts << endl;
return -1;
}
cout << Sharpness << endl;
cout << argv[1] << " " << argv[2] << endl;
cout << num << endl;
cout << image_path << endl;
cout << "OK" << endl;
return 0;
}
但是,我们使用的上面的代码,使用格式,就稍有区别,如下:
****.exe --参数名=**** --参数名=**** (2)
只要使用如上的形式,一般就不会再出现,我下面提到的问题了。
第一个问题,如何将输入参数传递给变量
关于这个问题,我发现网上的很多例子中并没有提到,其实很简单,如下:
<span style="font-size:18px;">string image_path;
int num;
boost::program_options::options_description opts("Help Message");
opts.add_options()
("help,h", "A example is->sharpness_clean.exe image_path")
//("image_path,I", boost::program_options::value<string>(&image_path)->default_value("E:/wu_test/pictures1/000000000.jpg"), "图片的路径")
//("num,n", boost::program_options::value<int>(&num)->default_value(10), "测试用");
("image_path,I", boost::program_options::value<string>(&image_path), "图片的路径")
("num,n", boost::program_options::value<int>(&num), "测试用");</span>
重点看最后两行中括号中的引用,就是用这种方式,将对应的参数传递到变量里,类似传递参数。
第二个问题,改变默认参数。
如上代码中,注释掉的两行,设置了默认值。如果我们在输入命令是,不输入对应参数则直接利用默认值。那么不想使用默认值,我们只能使用上面提到的第二种命令行输入参数的方式,才能改变默认值。