greg
greg

Reputation: 337

How to get an element from argv[]

This is C++

At the windows cmd line user types

p3.exe X <data.txt

where "p3.exe" is the program name,

"X" will be a 1, 2, or 3,

and "data.txt" is some text file program uses for input.

Inside the main method, I'm expecting argv[1] to equal the string X typed at the cmd line. In fact, if I do

wcout << argv[1]

the output is "X" as expected.

So now I do this,

int main(int argc, char* argv[])
{
     if (argc > 1)
     {
          if (argv[1] == "X")
          {
              //do stuff
          }
     }
     return 0;
}   // end main

But (argv[1] == "X") never evaluates to true

What am i missing or not understanding?

Upvotes: 2

Views: 3744

Answers (2)

Stephan Lechner
Stephan Lechner

Reputation: 35154

Use if(strcmp(argv[1],"X")==0) .... Should solve the Problem.

Upvotes: 0

interjay
interjay

Reputation: 110108

You can't compare C-style strings (char *) with == because it only compares the pointer and not the pointed-to string.

You can either use strcmp:

if (strcmp(argv[1], "X") == 0)

or make sure at least one side of the comparison is a C++ string:

if (std::string(argv[1]) == "X")

Upvotes: 4

Related Questions