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

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

问题描述

我想比较两个字符串。存储在文件中的一个,另一个来自用户(标准输入)进行检索。

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;
}

在这个程序中, 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|\n|\0|
+-+-+-+--+--+

要摆脱换行符做到这一点。
注意事项:不要使用的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, "\n")] = '\0';

+-+-+-+--+
|b|o|b|\0|
+-+-+-+--+

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

Now, strcmp should return 0...

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

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