为什么 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错了吗?
strcmp()0当字符串相等且字符串不能同时为"."and时返回".."。意味着 的一侧||将始终为非零,因此条件始终为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)
strcmp()在有差异的情况下返回非零(因此计算结果为true)。
还可以查看文档(下面的链接)。还可以看看std::string哪个提供了operator==()这样的任务。请参阅此答案以了解如何。
返回一个整数值,表示字符串之间的关系:零值表示两个字符串相等。大于零的值表示第一个不匹配的字符在 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如果字符串在字典顺序上分别在字典顺序上是先于、相等或后,则返回 -1、0 或 1。
要检查字符串是否相等,请使用strcmp(s1, s2) == 0.
因为当相等和不同时strcmp返回,至少两个 strcmp 中的一个正在返回,当任何条件不同时将返回 true ,你应该这样做......01 or -11 or -1||0
if(strcmp(ent->d_name, dot) == 0 || strcmp(ent->d_name, twoDots) == 0)
我== 0在每个 strcmp 之后添加
strcmp 本身不返回布尔值。相反,它返回一个 int。如果匹配,则为 0,如果不匹配,则为其他。所以这应该有帮助:
if(0 == strcmp(d_name, dot) || 0 == strcmp(d_name, twoDots)) {
// Other code here
}