Using the equality operator == to compare two strings for equality in C

前端 未结 9 662
悲&欢浪女
悲&欢浪女 2020-11-22 16:38
int main (int argc, **argv)
{
       if (argv[1] == \"-hello\")
            printf(\"True\\n\");
       else
            printf(\"False\\n\");
}
         


        
9条回答
  •  没有蜡笔的小新
    2020-11-22 17:23

    Because C strings dont exist as such. They are char arrays ending in a \0.

    The equality operator == will test that the pointer to the first element of the array are the same. It wont compare lexicographically.

    On the other hand "-hello" == "-hello" may return non zero, but that doesn't mean that the == operator compares lexicographycally. That's due to other facts.

    If you want to compare lexicographycally, you can always

    #define STR_EQ(s1,s2)    \
       strcmp(s1,s2) == 0
    

    Reading harder I see that you tagged as c++. So you could

     std::string arg1 ( argv[1] );
    
     if (arg1 == "-hello"){
        // yeahh!!!
     }
     else{
        //awwwww
     }
    

提交回复
热议问题