You are not logged in.

#1 2009-08-18 07:27:10

tpolich
Member
Registered: 2009-08-07
Posts: 44

[SOLVED] char* compare to string, c++

Ive been working on a program for my personal use and I getting to the point where I need command line arguments. For the life of me I can't get the compare to return true. Here is a bit of what I've been trying. If someone could show me or point me to somewhere that I could find how to do this, please.

int main(int argc, char* argv[]){
    std::cout<< argv[1];
    std::cout<< argc;
    std::cout<<(argv[1]=="-h");

}

That outputs

-h
2
0

I dont understand why it's false, I have even tried (argv[1] == "-h\0") to see if adding a null terminator would help.

Thank you in advance for the help.

Last edited by tpolich (2009-08-18 19:05:06)

Offline

#2 2009-08-18 08:56:38

wu.soldier
Member
From: Poland
Registered: 2006-12-19
Posts: 22

Re: [SOLVED] char* compare to string, c++

You get the wrong result because operator "==" compares addresses in that case. Note that argv[1] is not std::string type but char*. You may create std::string object from argv[1] and then use "==" operator:

std::cout << (std::string(argv[1]) == "-h");

provided that your c++ compiler will treat "-h" as std::string.

You can also try strcmp() function which operates on C strings ( char *). It returns 0 if C strings are equal so:

if(strcmp(argv[1], "-h") == 0) {
std::cout << "true";
}

Offline

#3 2009-08-18 10:50:54

krolden
Member
Registered: 2009-06-30
Posts: 12

Re: [SOLVED] char* compare to string, c++

checkout the getopt() function call.  This is a more elegant way of handling this.

Offline

#4 2009-08-18 19:04:51

tpolich
Member
Registered: 2009-08-07
Posts: 44

Re: [SOLVED] char* compare to string, c++

Thank you for the reply the std::string works. Also krolden I just started playing around with getopt() and I have to say its really really nice for what I'm doing.

Offline

Board footer

Powered by FluxBB