Search code examples
c++if-statementargv

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

Solution

  • 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.