1

I have code that is crashing:

    if(argc<2)
    {
      printf("Too few arguments\n");
    }
    else if(argc>=2)
    {
        namespace po = boost::program_options;
        po::options_description desc("Options");
        desc.add_options()
            ("c")
            ("d")
            ("filename", po::value<string>());

        po::variables_map vm;
        po::store(po::parse_command_line(argc,argv,desc),vm);
        po::notify(vm);
        if(vm.count("c"))
        {
          // option c
        }
        else if(vm.count("d"))
        {
          // option d
        }
    }

Debug Error: This application has requested the Runtime to terminate it in an usual way...

I want my program to have options -c and -d and optional filename after them. How to add_options into options_description and next how to check if I have option -c, -d and if I have filename as command line parameter?

I've read tutorial for boost/program_options from boost site, but I can't figure how to do it.

manlio
  • 18,345
  • 14
  • 76
  • 126
CppMonster
  • 1,216
  • 4
  • 18
  • 35
  • Did you come across [this example](http://www.boost.org/doc/libs/1_55_0/doc/html/program_options/tutorial.html#idp163291912), which uses `vm.count`? – chris Apr 15 '14 at 14:30
  • I improved my code, is that correct? – CppMonster Apr 15 '14 at 14:35
  • Something like that. It's been too long since I've used this. If it seems to work when tested, chances are it does. – chris Apr 15 '14 at 14:41

1 Answers1

2

The above didn't compile for me (boost 1_55_0).

I fixed and completed it:

#include <boost/program_options.hpp>
#include <boost/program_options/options_description.hpp>
#include <iostream>

int main(int argc, char** argv)
{
    if(argc<2)
    {
        printf("Too few arguments\n");
    }
    else
    {
        namespace po = boost::program_options;
        po::options_description desc("Options");
        desc.add_options()
            ("c", "")
            ("d", "")
            ("filename", po::value<std::string>()->default_value(""));

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

        std::cout << "c parsed: "  << vm.count("c") << "\n";
        std::cout << "d parsed: "  << vm.count("d") << "\n";
        std::cout << "filename: '" << boost::any_cast<std::string>(vm["filename"].value()) << "'\n";
    }
}

When called with e.g. --c --filename blablabla.txt it prints

c parsed: 1
d parsed: 0
filename: 'blablabla.txt'

See it Live On Coliru

sehe
  • 374,641
  • 47
  • 450
  • 633