How to get optional parameter value in formatting settings?

I am using the Boost program option, and I want to offer an option that has three ways:

  • If not defined
  • If defined, but no value
  • If defined with a value

For example, I have a program that works with a file like a.jpg, and I want to suggest the user to use it in the following scenarios:

myapp.exe a.jpg : process jpeg myapp.exe a.jpg -e : process jpeg and generate report at the same directory as a.jpg myapp.exe a.jpg -ec:\tmp\ : process jpeg and generate report at c:\tmp\ 

How can I do this using the parameters of the Boost program?

+6
source share
1 answer

You can achieve this effect by specifying value both default_value and implicit_value .

default_value will be used when the option is not specified at all. implicit_value will be used when the parameter is concrete without a value. If set, it will override the default and implicit values.

So, some code for this might look something like this:

 #include "boost/program_options.hpp" #include <iostream> #include <string> using namespace std; int main(int argc, char** argv) { namespace po = boost::program_options; po::options_description desc("Options"); desc.add_options() ("process-jpeg,e", po::value<string>()->default_value("")->implicit_value("./"), "Processes a JPEG."); po::variables_map vm; try { po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); } catch (po::error& e) { cerr << "ERROR: " << e.what() << endl << endl << desc << endl; return 1; } string outputDir = vm["process-jpeg"].as<string>(); if (outputDir.empty()) { cout << "-e was not provided on the command line" << endl; } else { cout << "-e is using directory: " << outputDir << endl; } } 

Running this example:

 $ ./jpg_processor -e was not provided on the command line $ ./jpg_processor -e -e is using directory: ./ $ ./jpg_processor -ec:\tmp -e is using directory: c:\tmp 
+9
source

All Articles