我正在尝试比较两个字符串。一个存储在文件中,另一个从用户 (stdin) 检索。
这是一个示例程序:
int main()
{
char targetName[50];
fgets(targetName,50,stdin);
char aName[] = "bob";
printf("%d",strcmp(aName,targetName));
return 0;
}
在此程序中,当输入为 "bob"
时,strcmp
返回值 -1。
为什么是这样?我认为他们应该是平等的。我怎样才能做到这一点?
最佳答案
strcmp
是少数具有 true 和 false 相反结果的函数之一...如果字符串相等,结果是 0,而不是您想象的 1...
if (strcmp(a, b)) {
/* Do something here as the strings are not equal */
} else {
/* Strings are equal */
}
说到fgets
,字符串末尾可能附加了一个换行符...您需要将其删除...
+-+-+-+--+--+
|b|o|b|\n|\0|
+-+-+-+--+--+
要摆脱换行符,请执行以下操作。 注意:不要使用“strlen(aName) - 1”,因为 fgets 返回的行可能以 NUL 字符开头 - 因此缓冲区的索引变为 -1:
aName[strcspn(aName, "\n")] = '\0';
+-+-+-+--+
|b|o|b|\0|
+-+-+-+--+
现在,strcmp
应该返回 0...
关于c - strcmp 在使用 fgets 读取的行上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34297667/