You are not logged in.
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
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
checkout the getopt() function call. This is a more elegant way of handling this.
Offline
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