Guranjan Singh
Guranjan Singh

Reputation: 734

passed command line paramenters

I'm writing a program where the user can pass in options such as, -e or -n, as command line parameters. But the following if loop doesn't work for some reason. I'm trying to run the program as: ./a.out -e test.html where test.html is the filename I'm parsing:

int main(int argc, char** argv) {
  ifstream inf;
    if(argv[1] == "-e")
        cout << "do somethin" << endl;
  else
        cout << "do something different" << endl;
  return 0;
}

Upvotes: 1

Views: 64

Answers (2)

chux
chux

Reputation: 154176

You are improperly comparing 2 strings. Change your if()

if(argv[1] == "-e")

to

if (strcmp(argv[1], "-e") == 0) {

Be sure to

#include <string.h>

Note: Although your code is C++ cout << ..., argv[1] is not a std:string, but s/b a const char *. Thus strcmp() is need to compare it directly to a quoted string. Alternatively you could:

#include <string>
if (std::string(argv[1]) == "-e")  { ...

Upvotes: 1

itsols
itsols

Reputation: 5582

Change the first line to this:

int main(int argc, char* argv[])
  1. It creates an array of argv
  2. Each element of argv can hold a string of chars

I assumed your code to be a segment of something larger. But here's the complete code if you're not sure...

#include <iostream>
#include <string>
using namespace std;

int main(int argc, char* argv[]) {

    if(argv[1] == "-e")
        cout << "do somethin" << endl;
  else
        cout << "do something different" << endl;
  return 0;
}

Upvotes: 1

Related Questions