Tawfiq Chowdhury
Tawfiq Chowdhury

Reputation: 41

How to handle command line arguments in C++ that has negative sign (-) in linux terminal?

I need this for an assignment. I know how standard command line input works in C++. if I have an executable named training, then I can write the following line in terminal:

./training input.text output1 output2

In that case my main method, would be like following:

int main( int argc, char* argv[] ){
     take_input( argv[1] );
     make_output( argv[2], argv[3] );
}

And my function declarations would be following:

int take_input( string filename );
int make_output( string filename, string filename2 )

However, I need to write the command line as follows:

training -i input.csv -os output1 -oh output2

I do not know how to make the modifications. Help will be much appreciated.

Upvotes: 1

Views: 873

Answers (2)

Jeremy Friesner
Jeremy Friesner

Reputation: 73171

getopt() will work, but if your needs are minimal and you don't want to add an external dependency, you can write your own little helper function to find where the dash-keywords are inside the argv array, like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Returns the index of the specified keyword (e.g. "-oh")
// or returns -1 if the keyword doesn't exist
static int find_keyword(int argc, char *argv[], const char * keyword)
{
   for (int i=0; i<argc; i++)
   {
      if (strcmp(argv[i], keyword) == 0) return i;
   }
   return -1;
}

int main( int argc, char* argv[] )
{
   const int iIndex = find_keyword(argc, argv, "-i");
   if (iIndex < 0) {printf("No -i keyword found!  Exiting!\n"); exit(10);}

   const int osIndex = find_keyword(argc, argv, "-os");
   if (osIndex < 0) {printf("No -os keyword found!  Exiting!\n"); exit(10);}

   const int ohIndex = find_keyword(argc, argv, "-oh");
   if (ohIndex < 0) {printf("No -oh keyword found!  Exiting!\n"); exit(10);}

   take_input( argv[iIndex+1] );
   make_output( argv[osIndex+1], argv[ohIndex+1] );
}

Note that the program as shown doesn't check to see if the next argument after the dash-argument exists; e.g. if you ran "./a.out -i foo -os bar -oh", then make_output's second argument would be passed in as NULL. You could modify find_keyword() to check for that possibility and return -1 in that case if you wanted to be extra-robust in your error-handling.

Upvotes: 2

Cyber
Cyber

Reputation: 867

On Linux you just include unistd.h and use getopt.

Upvotes: 0

Related Questions