Skip to content

Instantly share code, notes, and snippets.

@sidewinder040
Created June 7, 2025 16:36
Show Gist options
  • Save sidewinder040/8596e4b57406810af4c83972be571e8e to your computer and use it in GitHub Desktop.
Save sidewinder040/8596e4b57406810af4c83972be571e8e to your computer and use it in GitHub Desktop.
Boost Program_options Demo (for a RSS Reader
// rss-reader-opts.cpp
// This program demonstrates the use of Boost.ProgramOptions to handle command line arguments
// for a simple RSS reader application. It allows users to list, read, add, and delete feeds.
// To Build: clang++ -O3 -std=c++11 -lboost_program_options rss-reader-opts.cpp -o rss-read
#include <string>
#include <vector>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <iostream>
#include <iterator>
using namespace std;
int main(int ac, char* av[])
{
try {
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "produce help message")
("list,l","list available Feeds")
("read,r", po::value<int>(),"read Feed by ID")
// new option for adding feeds that takes two arguments. One for the feed name and another for the URL
("add,a", po::value<std::vector<std::string>>()->multitoken(), "add Feed with name and URL")
("delete,d", po::value<bool>(),"delete Feeds")
;
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 0;
}
if (vm.count("list")) {
cout << "Listing available Feeds.\n";
} else if (vm.count("read")) {
cout << "Reading Feed with ID: "
<< vm["read"].as<int>() << ".\n";
} else if (vm.count("add")) {
// Check if the vector has exactly two elements
if (vm["add"].as<std::vector<std::string>>().size() != 2) {
cerr << "Error: --add requires exactly two arguments: feed name and URL.\n";
return 1;
}
// Accessing the vector of strings for the feed name and URL
cout << "Adding Feed: "
<< "Feed Name: " << vm["add"].as<std::vector<std::string>>()[0] << "\n"
<< "Feed URL: " << vm["add"].as<std::vector<std::string>>()[1] << "\n";
} else if (vm.count("delete")) {
cout << "Deleting Feed.\n";
}
else {
cout << "No valid option provided.\n";
}
}
catch(exception& e) {
cerr << "error: " << e.what() << "\n";
return 1;
}
catch(...) {
cerr << "Exception of unknown type!\n";
}
return 0;
}
@sidewinder040
Copy link
Author

This is based on an example distributed with the Boost Documentation examples.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment