用 fgets 读取的一行上的 strcmp [英] strcmp on a line read with fgets

查看:22
本文介绍了用 fgets 读取的一行上的 strcmp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较两个字符串.一个存储在文件中,另一个从用户(标准输入)中检索.

I'm trying to compare two strings. One stored in a file, the other retrieved from the user (stdin).

这是一个示例程序:

int main()
{
    char targetName[50];
    fgets(targetName,50,stdin);

    char aName[] = "bob";
    printf("%d",strcmp(aName,targetName));

    return 0;
}

在这个程序中,当输入是"bob"时,strcmp返回值-1.为什么是这样?我认为他们应该是平等的.我怎样才能得到它呢?

In this program, strcmp returns a value of -1 when the input is "bob". Why is this? I thought they should be equal. How can I get it so that they are?

推荐答案

strcmp 是少数具有真假相反结果的函数之一......如果字符串相等,则结果是 0,而不是你想象的 1....

strcmp is one of the few functions that has the reverse results of true and false...if the strings are equal, the result is 0, not 1 as you would think....

if (strcmp(a, b)) {
    /* Do something here as the strings are not equal */
} else {
    /* Strings are equal */
}

说到fgets,有可能在字符串的末尾附加了一个换行符……你需要去掉它……

Speaking of fgets, there is a likelihood that there is a newline attached to the end of the string...you need to get rid of it...

+-+-+-+--+--+
|b|o|b|
||
+-+-+-+--+--+

要摆脱换行符,请执行此操作.警告:不要使用strlen(aName) - 1",因为 fgets 返回的行可能以 NUL 字符开头 - 因此缓冲区的索引变为 -1:

To get rid of the newline do this. CAVEATS: Do not use "strlen(aName) - 1", because a line returned by fgets may start with the NUL character - thus the index into the buffer becomes -1:

aName[strcspn(aName, "
")] = '';

+-+-+-+--+
|b|o|b||
+-+-+-+--+

现在,strcmp 应该返回 0...

Now, strcmp should return 0...

这篇关于用 fgets 读取的一行上的 strcmp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆