2013-11-14 117 views
1

我將const char *與一個字符串進行了比較,出於某種原因它總是成功。將const char *與strcmp進行比較

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? 

。 我如何獲得有效的比較?

+2

RTFM。認真。 –

+0

你睡得好嗎?來自這篇文章:http://stackoverflow.com/questions/2931704/how-to-compare-string-with-const-char這是一個相當容易的錯誤。 – clankill3r

回答

7

根據cplusplus.com

返回指示 串之間的關係的積分值:零值表示這兩個字符串相等。大於零的值 表示不匹配 的第一個字符在str1中的值比在str2中的值大;而小於 的值表示相反。

或者通過cppreference.com不同說:

返回值

  • 負值,如果LHS小於RHS。
  • 0如果lhs等於rhs。
  • 如果lhs大於rhs,則爲正值。

所以,在你的代碼,strcmp(t->detectColor->name, "ghghjg")將返回的東西比0不同的結果,「XXXXXXXXXXX」將被打印出來。

你只需要改變:

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

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

與同爲其他比較。

+0

使用更好的cppreference引用 – 4pie0

+0

@piotruś:你是說這個引用是錯誤的嗎?這對我來說看起來很好,但也許最好引用C標準而不是某個網站。 –

+0

@piotruś我已添加您的參考。我使用了cplusplus.com,因爲他們通常是Google的第一個成果,並且完成了這項工作。 –

0

std::strcmp當字符串相同時返回0,當字符串不同時返回值小於0或大於0。如果LHS小於RHS

if (std::strcmp(t->className, "IM_SURE_IT_CANT_BE_THIS") != 0) { 
    printf("indeed, strings are different\n"); 

負值:所以,你可能會改變你的代碼這樣的事情。 0如果lhs等於rhs。 正向值,如果lhs大於rhs。

http://en.cppreference.com/w/cpp/string/byte/strcmp


我怎樣才能得到有效的比較?

if (std::strcmp(t->className, "IM_SURE_IT_CANT_BE_THIS") == 0) { 
     printf("strings are equal lexicographically\n");