Skip to content

Instantly share code, notes, and snippets.

@yuya-oc
Created February 23, 2012 15:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yuya-oc/1893249 to your computer and use it in GitHub Desktop.
Save yuya-oc/1893249 to your computer and use it in GitHub Desktop.
boost::program_options sample
#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