gpt4 book ai didi

c++ - 比较 const char * 和 strcmp

转载 作者:太空狗 更新时间:2023-10-29 23:45:21 29 4
gpt4 key购买 nike

我将 const char * 与字符串进行比较,出于某种原因,它总是成功。

    if (std::strcmp(t->detectColor->name, "ghghjg") != 0) {
printf("XXXXXXXXXXX\n");
// check if it was allready a sequencer
if (std::strcmp(t->className, "IM_SURE_IT_CANT_BE_THIS") != 0) {
printf("what is going on?\n");

detectColor 名称始终类似于绿色或蓝色,例如,t->className 是“ofxDTangibleBase”。仍然打印

XXXXXXXXXXX
what is going on?

在控制台中。我怎样才能得到一个有效的比较?

最佳答案

根据 cplusplus.com :

Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.

或者由 cppreference.com 表示不同:

Return value

  • Negative value if lhs is less than rhs.
  • 0​ if lhs is equal to rhs.
  • Positive value if lhs is greater than rhs.

因此,在您的代码中,strcmp(t->detectColor->name, "ghghjg") 将返回不同于 0 的内容。因此,将打印“XXXXXXXXXXX”。

你只需要改变:

if (std::strcmp(t->detectColor->name, "ghghjg") != 0)

if (std::strcmp(t->detectColor->name, "ghghjg") == 0)

其他对比也一样。

关于c++ - 比较 const char * 和 strcmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19978672/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com