2

I have a c++ program whose main function looks something like this:

if(a.size == 2) {
    if(s1) {
        f1(a[0], a[1], "string1");
    }
    else{
        f1(a[0], a[1], "string2");
    }
}
if(a.size == 1) {
    if(s1) {
        f1(a[0], "string1");
    }
    else{
        f1(a[0], "string2");
    }
}
else {
    if(s1) {
        f1("string1");
    }
    else{
        f1("string2");
    }
}
...
...
...
...

where a and s1 are received from commandline options. It has many commandline options and many layers of if...else.. structures and looks even messier. Is there a way to improve?

qed
  • 22,298
  • 21
  • 125
  • 196
  • 3
    have a look on boost program options http://www.boost.org/doc/libs/1_55_0/doc/html/program_options.html – hansmaad May 11 '14 at 10:43
  • 2
    I'd recommend using [boost program options](http://www.boost.org/doc/libs/1_55_0/doc/html/program_options.html) – πάντα ῥεῖ May 11 '14 at 10:45
  • It seems as if you already have code that parses all the command-line options and deposits its results in variables like `a` and `s1`. Do you want to redesign/replace the code that produces these variables, or do you just want a neater way to process the data that have already been placed in these variables? – David K May 11 '14 at 10:52
  • These variables are already results of the boost parser, so I am looking for a way to better processing these variable, rather than a way to getting them. – qed May 11 '14 at 11:12
  • Initialize these variables to default values, then change them when the command line options say so. – Jongware May 11 '14 at 11:32

1 Answers1

1

Instead of this original code,

if(a.size == 2) {
    if(s1) {
        f1(a[0], a[1], "string1");
    }
    else{
        f1(a[0], a[1], "string2");
    }
}
if(a.size == 1) {
    if(s1) {
        f1(a[0], "string1");
    }
    else{
        f1(a[0], "string2");
    }
}
else {
    if(s1) {
        f1("string1");
    }
    else{
        f1("string2");
    }
}

assuming that there’s a missing else, do

auto const s = (s1? "string1" : "string2");
switch( a.size )
{
    case 0: f1( s ); break;
    case 1: f1( a[0], s ); break;
    case 2: f1( a[0], a[1], s ); break;
}

For example.


For the general problem of parsing command line arguments, check out getopt and various options parsers, e.g. in Boost.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331