Compare equality of char[] in C

后端 未结 5 2175
抹茶落季
抹茶落季 2020-12-06 17:52

I have two variables:

char charTime[] = \"TIME\";
char buf[] = \"SOMETHINGELSE\";

I want to check if these two are equal... using ch

5条回答
  •  攒了一身酷
    2020-12-06 18:29

    char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE";
    

    C++ and C (remove std:: for C):

    bool equal = (std::strcmp(charTime, buf) == 0);
    

    But the true C++ way:

    std::string charTime = "TIME", buf = "SOMETHINGELSE";
    bool equal = (charTime == buf);
    

    Using == does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.

提交回复
热议问题