Can strcmp() work with strings in c++?

懵懂的女人 提交于 2020-07-03 08:14:32

问题


I have this line of code

if(strcmp(ob[i].getBrand(), ob[j].getBrand()) > 0)

and I get this error

error C2664: 'strcmp' : cannot convert parameter 1 from 'std::string' to 'const char *'

Does that mean that strcmp doesnt work with strings, but instead it has to convert it to char?


回答1:


Don't use strcmp. Use std::string::compare which has the same behavior as strcmp.

if(ob[i].getBrand().compare(ob[j].getBrand()) > 0)

Or much better

if(ob[i].getBrand() > ob[j].getBrand())

Generally you should use std::string::compare when you have to test various cases where the strings will be different, e.g.

auto cmp = ob[i].getBrand().compare(ob[j].getBrand());

if(cmp == 0) ...
else if(cmp > 0) ...
else if(cmp < 0) ...

In this way you only have to do the comparison operation on the strings once.

However, in your case where it's somehow apparent that you only have to use the comparison result in a single case (I'm really assuming, as I don't know the context of the code given), then operator > will suffice, and is much easier on the eye (the brain!).




回答2:


If getBrand() gives a std::string just use > compare.




回答3:


Simply use .c_str() to convert a string to char array, then you are able to use strcmp().

But in your case, use > is better :)



来源:https://stackoverflow.com/questions/25360218/can-strcmp-work-with-strings-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!