Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

c++ - Comparing command parameter with argv[] is not working

I am trying to compare the parameter of command with argv[] but it's not working. Here is my code.

./a.out -d 1

In main function

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

if (argv[1] == "-d")

    // call some function here

}

But this is not working... I don't know why this comparison is not working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't compare strings using ==. Instead, use strcmp.

#include <string.h>

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

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

// call some function here

}

The reason for this is that the value of "..." is a pointer representing the location of the first character in the string, with the rest of the characters after it. When you specify "-d" in your code, it makes a whole new string in memory. Since the location of the new string and argv[1] aren't the same, == will return 0.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...