1

Possible Duplicate:
C String — Using Equality Operator == for comparing two strings for equality

Basic question here. I'm compiling this program in g++ and running it with a single -r argument, (./a.out -r) however it does not output the specified cout statement below. Is there anything wrong with this code?

#include <string>
using namespace std;

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

    if (argv[1] == "-r" ) {
        cout << "First arg is -r" << endl;
    }

    return 0;
}  
Community
  • 1
  • 1
thisiscrazy4
  • 1,905
  • 8
  • 35
  • 58

4 Answers4

6

You cannot compare string literals using ==, because what that does is compare pointers (i.e., memory addresses, which in this case are always going to be different).

Use strcmp or compare std::string objects instead:

if (strcmp(argv[1], "-r") == 0) { ... }

or

if (std::string(argv[1]) == "-r") { ... }
Jon
  • 428,835
  • 81
  • 738
  • 806
1

You can't compare string literals with ==. Use strcmp.

(Also, don't forget to check that argc is at least 2).

Andrei Tita
  • 1,226
  • 10
  • 13
1

One mistake in your code is you are comparing the address of the char array instead of comparing the values in the array. As people have said you can do it the C way using strcmp (although it's safer to use strncmp to avoid buffer overruns).

However, it's easier to use std::string in C++.

I would copy the args into a vector of strings.

#include <vector>
#include <string>

int main(int argc, char* argv[])
{
    vector<string> args(argv, argv+argc);
    ...
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

Usually you would do something along these lines:

while (--argc && **++argv=='-')
{
   char *p;
    p=*argv+1;
    switch(tolower(*p))
    {
        case 'r':                                       
            break;

    }
}

basically, while there are some args left, check that there is a '-' char, then switch on the next char to see the modifier ('r', or 'a' etc)

Daboyzuk
  • 449
  • 4
  • 14