cxxopts
cxxopts copied to clipboard
Optional output file values
I have been trying various options with this handy library. But I hit a roadblock with a certain scenario. I would like to ask the program to generate output files using the following:
options.add_options()
("s,source", "Source input file",
cxxopts::value<std::string>())
//("d,debug", "Enable debugging") // a bool parameter
("p,splitoutput", "Split the output to separate files",
cxxopts::value<bool>()->default_value("false"))
("o,outfile", "Output file(s), separated by \',\' if multiple output "
"files (only if -p or --splitoutput is set) needed. The "
"order is - main, submodule1,submodule2, submodule3.",
cxxopts::value<std::vector<std::string>>()->default_value("default"))
("v,verbose", "Verbose output",
cxxopts::value<bool>()->default_value("false"))
("h,help", "Print usage")
Now, this requires me to pass at least one argument after -o
or --outfile
. I would like to make this optional and assign values internally if the user choses not to. For example,
./program -o
./program -o a.txt,b.txt,c.txt,d.txt
./program -o a.txt,,c.txt,d.txt
./program -o a.txt,,,d.txt
should all be possible.
I did the following (in addition to adding default_value
as well):
std::vector<std::string> o_files;
if (result.count("outfile"))
o_files = result["outfile"].as<std::vector<std::string>>();
else
o_files.push_back("defaults");
So that I can check for vector with "defaults" and process.
But I get the error:
terminate called after throwing an instance of 'cxxopts::missing_argument_exception'
what(): Option ‘o’ is missing an argument
Aborted
What is going wrong here? Is default_option
meant to work with only bool
types? Or am I missing something here?
If you want -o
to work by itself then you need an implicit argument. A default is so that you still get a value when -o
is not provided at all. However it makes parsing a bit difficult because it's ambiguous when you write:
-o argument
It is possible that the user meant -o
with implicit value, and argument
is a positional argument. So the only way to write that correctly is to use a long option and write --output=argument
.