Comparing command parameter with argv[] is not working

后端 未结 4 2051
温柔的废话
温柔的废话 2021-01-17 16:01

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



        
4条回答
  •  别那么骄傲
    2021-01-17 16:39

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

    #include 
    
    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.

提交回复
热议问题