我从一本书(Boost C ++应用程序开发指南)中获得了这段代码,并尝试运行它,并使用g ++进行了编译,但是当我尝试运行它时,它给了我这个错误“在抛出'boost :: exception_detail实例后终止调用: :clone_impl>'
what():未知的选项范围
中止(核心已弃用)”
它没有用clang编译,
我使用“ g ++ ex1.cxx -lboost_program_options”和“ clang ex1.cxx -lboost_program_options”进行了编译
#include <boost/program_options.hpp>
#include <boost/program_options/errors.hpp>
#include <iostream>
namespace opt = boost::program_options;
int main(int argc, char* argv[]){
opt::options_description desc("All options");
// 'a' and 'o' are short option names for apples
desc.add_options()("apple,a", opt::value<int>()->default_value(10),
"apples that you have")
("oranges,o", opt::value<int>(), "oranges that you have")("name",
opt::value<std::string>(), "your name")("help", "produce help message");
opt::variables_map vm;
opt::store(opt::parse_command_line(argc, argv, desc), vm);
opt::notify(vm);
if(vm.count("help")){
std::cout << desc << "\n";
return 1;
}
try{
opt::store(opt::parse_config_file<char>("apples_oranges.cfg", desc), vm);
}
catch(const opt::reading_file& e){
std::cout << "Failed to open 'apples_oranges.cfg': " << e.what();
}
opt::notify(vm);
if(vm.count("name")){
std::cout << "Hi, "<< vm["name"].as<std::string>() << "!\n";
}
std::cout << "Fruits count: "
<< vm["apples"].as<int>() + vm["oranges"].as<int>() << std::endl;
return 0;
}
最佳答案
这里有错字
vm["apples"].as<int>();
应该
vm["apple"].as<int>();
看到Live On Coliru
#include <boost/program_options.hpp>
#include <boost/program_options/errors.hpp>
#include <iostream>
namespace opt = boost::program_options;
int main(int argc, char* argv[]){
opt::options_description desc("All options");
// 'a' and 'o' are short option names for apples
desc.add_options()
("apple,a", opt ::value<int>()->default_value(10), "apples that you have")
("oranges,o", opt ::value<int>(), "oranges that you have")
("name", opt ::value<std::string>(), "your name")
("help", "produce help message");
opt::variables_map vm;
opt::store(opt::parse_command_line(argc, argv, desc), vm);
opt::notify(vm);
if(vm.count("help")){
std::cout << desc << "\n";
return 1;
}
try{
opt::store(opt::parse_config_file<char>("apples_oranges.cfg", desc), vm);
}
catch(const opt::reading_file& e){
std::cout << "Failed to open 'apples_oranges.cfg': " << e.what();
}
opt::notify(vm);
if(vm.count("name")){
std::cout << "Hi, "<< vm["name"].as<std::string>() << "!\n";
}
int a_ = vm["apple"].as<int>();
int o_ = vm["oranges"].as<int>();
std::cout << "Fruits count: " << a_ + o_ << std::endl;
}