Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using if/then statements to parse argv[ ] options in C++

How would you use an if/then statement using argv[], upon the option/parameter entered?

For example, a.out -d 1 sample.txt versus a.out -e 1 sample.txt.

int main (int argc, char *argv[])
{
  ifstream infile(argv[3]);

  int c;
  int number = 0;
  int count = 0;

  while ( infile.good() ) {

            if (argv[1] == "-d")
            {

                 c = infile.get();

                 number = atoi(argv[2]);  

                  if (number == count)
                 {
                 cout.put(c);
                 count = 0;
                 }

                      else
                        count++;

            }       


           if (argv[1] == "-e")
           { 
              cout << "entered -e" << endl;   //testing code
           }


  }//end while

}//end main
like image 259
harman2012 Avatar asked Oct 26 '25 07:10

harman2012


2 Answers

You can't use the equality operator to compare C-style strings, you have to use std::strcmp:

if (std::strcmp(argv[1], "-d") == 0)

The reason behind that is that the == operator compares the pointers not what they point to.


Since the C++14 standard, there's a literal operator to turn a literal string into a std::strinng object which can be used for comparisons using ==:

if (argv[1] == "-d"s)

Please note the trailing s in "-d"s.

like image 75
Some programmer dude Avatar answered Oct 27 '25 20:10

Some programmer dude


I hope you want to check the input parameter -d or -e, right? if that is the case please use strcmp()

if (!strcmp(argv[1],"-d")) {

            count++;
            printf("\ncount=%d",count);

        }       

       if (!strcmp(argv[1],"-e"))
       { 
          printf("entered -e");   //testing code
       }
like image 25
Azeem Sheikh Avatar answered Oct 27 '25 20:10

Azeem Sheikh