2

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?

greg
  • 338
  • 7
  • 17

2 Answers2

4

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")
interjay
  • 107,303
  • 21
  • 270
  • 254
  • Both work perfectly. So the 2nd answer works by "casting" the argv[1] pointer to a string? – greg Feb 19 '17 at 19:48
  • Yes, it copies the C string into a temporary std::string object, which is used to perform the comparison. If you wanted to compare `argv[1]` with multiple values, you can create the string in a separate line and then compare it with each value. – interjay Feb 19 '17 at 19:57
0

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

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58