Created
February 23, 2012 15:14
-
-
Save yuya-oc/1893249 to your computer and use it in GitHub Desktop.
boost::program_options sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/program_options.hpp> | |
// コンパイル時に-lprogram_optionsを指定 | |
namespace po = boost::program_options; | |
/** | |
* main function | |
*/ | |
int main(int argc, char** argv) { | |
std::string str; | |
po::options_description options("Allowed options"); | |
options.add_options() | |
// オプションの型をvalueで指定 | |
("int",po::value<int>(),"intオプション") | |
// デフォルト値や、格納先アドレスを指定できる | |
("char",po::value<char>()->default_value('a'),"charオプション") | |
("string",po::value<std::string>(&str),"stringオプション") | |
// 複数個受け取ることもできる | |
("vector",po::value<std::vector<std::string> >(),"vector<string>オプション") | |
// 省略形を設定できる | |
("help,h","show help") | |
; | |
// vmにオプションの値が格納される | |
po::variables_map vm; | |
try{ | |
po::store(po::parse_command_line(argc,argv,options),vm); | |
po::notify(vm); | |
} | |
catch(po::unknown_option unknown){ | |
std::cout << "Unknown option: " << unknown.get_option_name() << std::endl; | |
return 1; | |
} | |
// variables_map::count()でオプションが指定されたか調べる | |
if(vm.count("help")){ | |
// coutに入れるだけでオプションの説明を出力 | |
std::cout << options << std::endl; | |
return 0; | |
} | |
if(vm.count("int")){ | |
// インデクサを使って取り出す | |
std::cout << "int: " << vm["int"].as<int>() << std::endl; | |
} | |
std::cout << "char: " << vm["char"].as<char>() << std::endl; | |
// 指定した変数に格納されている | |
if(vm.count("string")){ | |
std::cout << "string: " << str << std::endl; | |
} | |
if(vm.count("vector")){ | |
std::vector<std::string> v = vm["vector"].as<std::vector<std::string> >(); | |
std::cout << "vector<string>: "; | |
for(unsigned int i=0;i<v.size();++i){ | |
std::cout << v[i] << " "; | |
} | |
std::cout << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment