jyim
jyim

Reputation: 119

command line option

#include <iostream>
#include <cstdlib>
#include <sstream>
#include <fstream>
using namespace std;

    int main(int argc, char* argv[]) 
    {
    cout << argv[1] << endl;
    if (argv[1]=="-r") cout << "success\n";
    }

"success" does not print out. When I run: $ ./hearts -r the only thing that comes out is:

-r

which makes me sooo confused

Upvotes: 1

Views: 165

Answers (6)

Moha Dehghan
Moha Dehghan

Reputation: 18443

In C, string are character-arrays (pointers to a sequence of characters). In your code, equality operator just compares two pointer values, which are absolutely different. You should use strcmp function, or use string class:

#include <iostream>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <cstring> // <-- here

using namespace std;

int main(int argc, char* argv[]) 
{
    cout << argv[1] << endl;
    if (strcmp(argv[1], "-r") == 0) // <-- and here
        cout << "success\n";
}

OR

#include <iostream>
#include <cstdlib>
#include <sstream>
#include <fstream>
#include <string> // <-- here

using namespace std;

int main(int argc, char* argv[]) 
{
    cout << argv[1] << endl;
    if (string(argv[1]) == "-r") // <-- and here
        cout << "success\n";
}

Upvotes: 1

Joseph Mansfield
Joseph Mansfield

Reputation: 110648

I'm going to go ahead and tell you that you don't want strcmp. The C++ way to handle command-line arguments is to turn them into std::strings as soon as possible:

int main(int argc, const char* argv[])
{
  // Make a vector of all command-line arguments
  std::vector<std::string> args(argv, argv+argc);
  // Now we can use std::string's operator==
  if (args.size() > 1 && args[1] == "-r") {
    std::cout << "Success" << std::endl;
  }
  return 0;
}

You can compare two std::strings with the == operator. In the case of args[1] == "-r", the const char[] string literal is converted to a std::string for comparison. In your code, argv[1]=="-r" compares two independent pointers which will not be equal - it does not compare the contents of the C-style strings.

Upvotes: 3

srbhkmr
srbhkmr

Reputation: 2104

You should try using:

if (strcmp(argv[1],"-r")==0) cout << "success\n";

to compare the argument with string literal.

Upvotes: 1

mvp
mvp

Reputation: 116048

You should use strcmp() and it will work as expected. When you use == you compare pointers, and they cannot be the same.

Upvotes: 1

melpomene
melpomene

Reputation: 85757

That's because you're using == on two pointers. It will check whether the pointers are equal, not whether the point at the same data.

To compare two C strings, use strcmp like this:

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

Upvotes: 2

Vlad
Vlad

Reputation: 18633

You probably want strcmp to compare the two strings. For == to be true, your two strings would have to refer to the same memory location, which can't happen, as "-r" is a compile-time constant.

Upvotes: 1

Related Questions