Bob John
Bob John

Reputation: 3878

Comparing arguments passed in the terminal through char *argv[] in main

I've been having trouble with the terminal, but I was wondering if something like this is legal:

int main(int argc, char *argv[])
{
    if(argv[3] = "today")
    {
        //do something
    }
}

Otherwise, can I compare them using c-strings?

Upvotes: 1

Views: 404

Answers (5)

fredoverflow
fredoverflow

Reputation: 263128

int main(int argc, char *argv[])
{
    std::vector<std::string> arguments(argv, argv + argc);
    if (arguments[3] == "today")
    {
        //do something
    }
}

Upvotes: 2

David Hammen
David Hammen

Reputation: 33116

That will always return false. You are comparing two addresses, not two strings. What you want to do is to compare the contents of those addresses, or compare strings themselves.

In C the preferred approach is to use the function strcmp:

if (strcmp(argv[3], "today") == 0) {
   // Do something
}

In C++, use strings:

if (std::string("today") == argv[3]) {
   // Do something
}

Upvotes: 0

taufique
taufique

Reputation: 2751

char* or arrays can't be compared with = operator. You need to use strcmp() function

int main(int argc, char *argv[])
{
    if(strcmp(argv[3], "today") == 0)
    {
        //do something
    }
}

Upvotes: 0

Corbin
Corbin

Reputation: 33447

No, that's not legal syntactically or logically.

You need to use strcmp.

if (argc >= 4 && strcmp(argv[3], "today") == 0) {
    //matched
}

(Or, as Dietmar Kühl suggested, you could use std::string and much simplify your coding life.)

Upvotes: 3

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153840

The program arguments are just pointers to char arrays. You are comparing pointers rather than the string content. The easiest way is to compare the arguments using std::string, e.g.:

if (argv[3] == std::string("today")) {
    ...
}

Upvotes: 2

Related Questions