Reading command line arguments and setting up values if option not provided


 
Thread Tools Search this Thread
Top Forums Programming Reading command line arguments and setting up values if option not provided
# 1  
Old 03-22-2012
Reading command line arguments and setting up values if option not provided

I have a C++ program. I read command line arguments, but if the value is not supplied, I default or make a calculation. Let's say I set it to a default value.

I can code this in several ways. Here I show three ways. What would be the best way for maintaining this code? The program will get very large with lot of options, so need a scheme that can facilitate the development and maintenance of the code .

Code:
   Parsing  Pc(argc, argv);           // Pass all arguments
 
  const double  DefdAng = 2.0;
   double  dAng = DefdAng;
   if (Pc.GetDouble("DANG", dAng)) {   // User supplied value for dAng using DANG option. 
       cout << "User supplied dAng value = " << dAng << endl;
  }

Code:
  Parsing  Pc(argc, argv);           // Pass all arguments

  const double  DefdAng = 2.0;
  double  dAng;
  if (Pc.GetDouble("DANG", dAng)) {   // User supplied value for dAng using DANG option. 
      cout << "User supplied dAng value = " << dAng << endl;
  else {
      dAng = DefdAng;
       cout << "dAng set to default value of " << dAng << endl;
   }

Code:
   Parsing  Pc(argc, argv);           // Pass all arguments
 
  const double  DefdAng = 2.0;
   double  dAng;
   if (!Pc.GetDouble("DANG", dAng)) {
       dAng = DefdAng;
         cout << "dAng set to default value of " << dAng << endl;
     else {      // User supplied value for dAng using DANG option. 
      cout << "User supplied dAng value = " << dAng << endl;
    }

# 2  
Old 03-22-2012
You've not defined any of your classes as usual so I have no idea what any of your code is doing.

The easiest way to set a default is to just set the value in the first place. If there's another value found, overwrite the original.

Code:
int var=32;

if(has_value) var=get_value;

# 3  
Old 03-22-2012
Here is a bit about class Parsing

Code:
#ifndef Parsing_hh
#define Parsing_hh

#include <iostream>
#include <fstream>
#include <string.h>

#include "ParseEl.hh"
#include "DynBaseObj.hh"
#include "List.hh"
#include "Stack.hh"
#include "Tree.hh"
#include "Vect2.hh"
#include "Vector.hh"
#include "String.hh"
#include "common.hh"

class Parsing {

private:

  int  Length;                         //
  int  Ptr;                            //
  List<ParseEl>  Index;                //

public:

  Parsing();                           //

  Parsing(                             //
    const int  argc,
    char*  argv[]);

  void  ParseCmd(                      // Read command line arguments.
    const int  argc,
    char*  argv[]);

  bool  GetDouble(                     // Get a double precision number.
    const String&  Id,
    double&  d,
    const int  ord1,
    const int  ord2,
    const int  ord3);

  bool  GetDouble(                     // Get a double precision number.
    const char*  Id,
    double&  d,
    const int  ord1,
    const int  ord2,
    const int  ord3);

private:

  bool  GetDouble(                     // Get a double precision number.
    const char*  Id,
    double&  d,
    const List<int>&  ord);

};

////////////////////////////////////////////////////////////////////////////////////////////////////

inline Parsing::Parsing() {
  Ptr = 0;
}

////////////////////////////////////////////////////////////////////////////////////////////////////

Parsing::Parsing(
  const int  argc,
  char*  argv[]) {

  ParseCmd(argc, argv);

}

////////////////////////////////////////////////////////////////////////////////////////////////////

// Reading arguments from the command line

void  Parsing::ParseCmd(
  const int  argc,
  char*  argv[]) {

  int  i;
  int  StrSize;                        // Size of string
  int  EndsSize;                       // Size of string
  int  poseq;
  const char* Name;
  const char* Ends;
  String  SName;
  String  SEnd;

  List<int>  Ord;
  Ord += 0;

  for (i = 1; i < argc; i++) {

      // First character is '?', e.g. "?abcd"[0] is '?'.
      if (argv[i][0] == '?') {

          ifstream ifs(argv[i]+1);     // "?abcd"+1 is "abcd", so open filename "abcd".
          if ( ifs.bad() ) error("Error including file " + String(argv[i]) );
          else ParseFile(ifs);

      }                                // end of code block. ifs closes here.

      // First 2 chars are '-'. A zero value indicates that the characters compared in both
      // strings are all equal.
      else if (strncmp(argv[i], "--", 2) == 0)
      {

          // Pointer to first occurrence of '='
          // strchr("--asdf=b", '=') is "=b". If '=' is not found, function returns null pointer.
          const char* After = strchr(argv[i], '=');

//          String Name;                 // Make it a 'String' so we can use ToUpper.

          // '=' is not found. Get user input from next argument.
          if (After == NULL)
          {
            SName = String(argv[i]);   // Conversion of 'Name' to a 'String' so we can use ToUpper.
            i++;                       // ++i is more efficient than i++.
            if (i == argc) {           // If next argument not found, quit instead of crashing.
              error("Out of arguments");
              continue;
            }
            Ends = argv[i];            // Set user input
            SEnd = String(Ends);

          // '=' is found.
          } else {
            String S = String(argv[i]);
            Search(S, "=", poseq);
            SName = ToUpper( S.Substr(2, poseq-1) );
            Ends = After + 1;          // Set user input. "=file"+1 is "file".
            SEnd = String(Ends);
          }

          cout << "Name = " << SName << ", Ends = " << SEnd << endl << endl;
          Index += ParseEl(SName, SEnd, Ord);

      } else {

          String Msg = "Long options must be introduced by a double dash '--'. '";
          error(Msg + String(argv[i]) + "'");

      }

  }

  Ptr = 0;

}

////////////////////////////////////////////////////////////////////////////////////////////////////

inline bool  Parsing::GetDouble(
  const String&  Id,
  double&  d,
  const int  ord1 = 0,
  const int  ord2 = 0,
  const int  ord3 = 0) {

  return GetDouble( (char *)Id, d, ord1, ord2, ord3 );

}

////////////////////////////////////////////////////////////////////////////////////////////////////

bool  Parsing::GetDouble(
  const char*  Id,
  double&  d,
  const int  ord1 = 0,
  const int  ord2 = 0,
  const int  ord3 = 0 ) {

  List<int>  L;

  if (ord1 != 0) {
      L += ord1;
      if (ord2 != 0) {
          L += ord2;
          if (ord3 != 0) { L += ord3; }
      }
  }

  return GetDouble(Id, d, L);

}

////////////////////////////////////////////////////////////////////////////////////////////////////

bool  Parsing::GetDouble(
  const char*  Id,
  double&  d,
  const List<int>&  ord) {

  int  j;
  int  found = -1;
  int  HId = Hash(Id);

  j = Ptr;
  if (Index.size() == 0) { return false; }

  do {

      if ( (Index[j].Hash == HId) && (Index[j].Type == PARAM)
        && (Index[j].Name == String(Id)) && (Index[j].Ord == ord) ) {
          found = j;
      }

      j++;
      if (j == Index.size()) { j = 0; }

  } while ((found == -1) && (j != Ptr));

  if (found == -1) { return false; }
  Index[found].Str.Rewind();
  Index[found].Str >> d;
  Ptr = found;
  if (Ptr == Index.size()) { Ptr = 0; }
  return true;

}

////////////////////////////////////////////////////////////////////////////////////////////////////

#endif

---------- Post updated at 08:16 PM ---------- Previous update was at 08:05 PM ----------

Quote:
Parsing Pc(argc, argv);
Take all command line arguments defined as --name=value.
Stores the list of names and the corresponding values.

Quote:
Pc.GetDouble("DANG", dAng)
Checks if DANG is present in the name list. If successful,
the function will return true and the value returned in the
variable dang. Otherwise returns false.
Login or Register to Ask a Question

Previous Thread | Next Thread

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Reading properties from file and setting variable values

I want to read properties from a file and print evaluated values of each key. I am using AIX6.1. myfile.props protocol=http siteA.host=siteAhostname pageA=pageNameA siteAURL1=${protocol}:/${siteA.host}/pagea/blabla?v1=32 siteAURL2=${protocol}:/${siteA.host}/${pageA}/blabla?v1=32... (5 Replies)
Discussion started by: kchinnam
5 Replies

2. Shell Programming and Scripting

Read file lines and pass line values as arguments.

Dears, Need help to implement below requirement A file (detail.txt)contain : 1st column: Stream 2nd column: PathAddress 3rd column: Counterlimit 4th column: TransactionDateColumn 5th column: DateType 6th column: SleepValue 7th column: Status Need to write a... (1 Reply)
Discussion started by: sadique.manzar
1 Replies

3. Shell Programming and Scripting

Replace values in script reading line by line using sed

Hi all, Let's say I have a script calling for the two variables PA_VALUE and PB_VALUE. for pa in PA_VALUE blah blah do for pb in PB_VALUE blah blah do I have a text file with two columns of values for PA and PB. 14.5 16.7 7.8 9.5 5.6 3.6 etc etc I would like to read this... (7 Replies)
Discussion started by: crimsonengineer
7 Replies

4. Shell Programming and Scripting

Awk: Comparing arguments with in line values of file and printing the result

I need to develop a script where I will take two date arguments as parameter date1 and date2 which will in format YYYYMM. Below is the input file say sample.txt. sample.txt will have certain blocks starting with P1. Each block will have a value 118,1:TIMESTAMP. I need to compare the... (7 Replies)
Discussion started by: garvit184
7 Replies

5. Shell Programming and Scripting

Reading multiple values from multiple lines and columns and setting them to unique variables.

Hello, I would like to ask for help with csh script. An example of an input in .txt file is below, the number of lines varies from file to file and I have 2 or 3 columns with values. I would like to read all the values (probably one by one) and set them to independent unique variables that... (7 Replies)
Discussion started by: FMMOLA
7 Replies

6. Shell Programming and Scripting

Command line arguments with multiple values

how can I pass multiple values from command line arguments example script.sh -arg1 op1 -arg2 op1 op2 op3 (2 Replies)
Discussion started by: nsk
2 Replies

7. UNIX for Dummies Questions & Answers

Command line / script option to filter a data set by values of one column

Hi all! I have a data set in this tab separated format : Label, Value1, Value2 An instance is "data.txt" : 0 1 1 -1 2 3 0 2 2 I would like to parse this data set and generate two files, one that has only data with the label 0 and the other with label -1, so my outputs should be, for... (1 Reply)
Discussion started by: gnat01
1 Replies

8. Homework & Coursework Questions

trouble understanding file option and command line arguments

Hi, I am creating a program with the C language that simulates the WC command in Unix. My program needs to count lines, bytes and words. I have not added the code to count bytes and words yet. I am having trouble understanding what the file option/flag '-' does. I can not visualize how it moves... (1 Reply)
Discussion started by: heywoodfloyd
1 Replies

9. UNIX and Linux Applications

Reading values from the command line

Hi I want to give the user the choice of whether or not they want to include a certain option when they run the script. This is my getops: while getopts " s: d: r f: e h " option do case $option in f ) dsxfile="$OPTARG";; d ) dbname="$OPTARG";; s ) dsn="$OPTARG";; r )... (0 Replies)
Discussion started by: ladyAnne
0 Replies

10. Shell Programming and Scripting

Bash: Reading 2 arguments from a command line

If no arguments are entered I wanna be able to read 2 arguments, i have done like this but it doesnt work: x=0 until #loop starts do if ; then echo No arguments were entered, please enter 2 arguments. read $1 $2 elif || ; then echo $#... (0 Replies)
Discussion started by: Vozx
0 Replies
Login or Register to Ask a Question