CGとCVの日記

Computer GraphicsとComputer Visionについて

boost::program_options

c++コマンドライン引数をパースするライブラリを探してたら2つ見つかった.

http://www.gnu.org/s/hello/manual/libc/Getopt.html
シンプルで使いやすい.Java移植版もある

  • boost::program_options

やっぱりboostにもあった.
使うのはとても簡単.エラーやヘルプのメッセージなどが自動生成されるので楽.

#include <boost/program_options.hpp>

using namespace std;
namespace po = boost::program_options;

po::options_description desc("Allowd options");
po::variables_map vm;

string input_filename;

void parse_program_options(int argc, char** argv){

	desc.add_options()
			("help,h","produce help message")
			("input,i", po::value<string>(), "input file name")
			;

	po::store(po::parse_command_line(argc, argv, desc), vm);
	po::notify(vm);

	  if(vm.count("help")){
		cout << desc << endl;

	  }
	  if(vm.count("input")){
		  if(vm["input"].as<string>().empty()){
			  cerr << "input file name is empty" << endl;
			  exit(-1);

		  }
		  else{
			  cout << "input file name is " << vm["input"].as<string>() << endl;
			  input_filename = vm["input"].as<string>();
		  }
	  }
}

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

	parse_program_options(argc, argv);
        
        return 0;

}

boost::program_options::parse_config_fileを使えばコマンドラインだけじゃなくconfig fileからも簡単にできそう.