【问题标题】:strcmp always truestrcmp 始终为真
【发布时间】:2012-08-17 21:07:18
【问题描述】:

为什么 if 语句总是正确的?

char dot[] = ".";
char twoDots[] = "..";
cout << "d_name is " << ent->d_name << endl;
if(strcmp(ent->d_name, dot) || strcmp(ent->d_name, twoDots))

我用strcmp 错了吗?

【问题讨论】:

标签: c++ strcmp


【解决方案1】:

strcmp() 返回0,当字符串相等且字符串不能同时为"."".." 时。这意味着|| 的一侧将始终为非零,因此条件始终为true

纠正:

if(0 == strcmp(ent->d_name, dot) || 0 == strcmp(ent->d_name, twoDots))

另一种方法是使用std::string 来存储点变量并使用==

#include <string>

const std::string dot(".");
const std::string twoDots("..");

if (ent->d_name == dot || ent->d_name == twoDots)

【讨论】:

  • 我更喜欢! 而不是0 ==
【解决方案2】:

strcmp() 在有差异的情况下返回非零值(因此计算结果为true)。

还可以查看文档(下面的链接)。还可以查看std::string,它为此类任务提供了operator==()方法this answer


返回一个整数值,表示字符串之间的关系: 零值表示两个字符串相等。 大于零的值表示第一个不匹配的字符在 str1 中的值大于在 str2 中的值;而小于零的值则相反。


每个函数的返回值表示 string1 到 string2 的字典关系。

Value   Relationship of string1 to string2

 < 0    string1 less than string2
   0    string1 identical to string2
 > 0    string1 greater than string2

【讨论】:

  • strcmp 期望char * 时,怎么会在std::string 上工作?
  • @Celeritas strcmp 不适用于std::string(除非您订购了相应的以零结尾的C-string)。要测试等效性,您只需使用s1 == s2
【解决方案3】:

strcmp 分别返回 -1、0 或 1,如果字符串按字典顺序分别在字典序上是在前、相等或后。

要检查字符串是否相等,请使用strcmp(s1, s2) == 0

【讨论】:

    【解决方案4】:

    因为strcmp 相等时返回01 or -1 不同时返回,所以两个strcmp 中至少有一个返回1 or -1,当任何条件与0 不同时|| 将返回true ,你应该这样做......

    if(strcmp(ent->d_name, dot) == 0 || strcmp(ent->d_name, twoDots) == 0)
    

    我在每个 strcmp 之后添加了== 0

    【讨论】:

      【解决方案5】:

      strcmp 本身不返回布尔值。相反,它返回一个 int。如果匹配,则为 0,如果不匹配,则为其他。所以这应该会有所帮助:

      if(0 == strcmp(d_name, dot) || 0 == strcmp(d_name, twoDots)) {
          // Other code here
      }
      

      【讨论】:

        猜你喜欢
        • 2016-02-16
        • 1970-01-01
        • 1970-01-01
        • 2012-11-23
        • 2015-12-05
        • 2019-02-01
        • 2021-01-07
        • 2014-07-17
        • 1970-01-01
        相关资源
        最近更新 更多