STRCMP功能不能正常工作 [英] strcmp function not working properly

查看:226
本文介绍了STRCMP功能不能正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 删除功能结构上的图书 的数组。我传递给它的记录数组,一书的作者书的名字列表的大小

I have a delete function on array of structures books. I'm passing it an array of records, author of book and name of book and size of the list.

现在这里的因为列表[0] .author 列表[5] .author 作者都是等于丹·布朗(相同的字符串)

Now here given that list[0].author and list[5].author and author all are equal to "Dan Brown" (same string)

void delete(struct books *list,char author[],char name[],int n)
{
    int i,a;
    a=strcmp(list[0].author,list[5].author);
    printf("%d\n",a);              // prints 0
    a=strcmp(list[0].author,author);
    printf("%d\n",a);              // prints other than 0
}    

为什么会发生?什么是错在这里?

Why is it happening? What's wrong here?

推荐答案

<文档code>与fgets

阅读停止。 新行,如果有的话,将被保留。

这意味着与fgets 不可以删除最后一个的'\\ n'从读出字符串的结尾。因此,你的字符串是:

This means that fgets will not remove the final '\n' from the end of the read string. Thus, your strings are:


  1. 丹·布朗的

  2. 丹·布朗的

  3. 丹·布朗\\ n

他们的不可以相等的。

这使用与fgets 的时候是一个非常普遍的问题。这就是为什么我通常preFER scanf函数,就像这样:

This is a very common issue when using fgets. That's why I usually prefer scanf, like this:

char buffer[BUF_LEN];
char format[16];
int scanf_result;

sprintf(format, "%%%u[^\n]", BUF_LEN);
//....
do
{
  //TODO: Ask for input
  scanf_result = scanf(format, buffer);
  switch (scanf_result)
  {
    case -1: //TODO: Print error message and exit
    case 0: //TODO: Print error mesage and break
  }
  //Discard remainings of buffered input line
  while (getchar() != '\n') {;}
} while (1); //Ugly, but plain

否则,您可以使用与fgets 的东西是这样的:

int buf_len;

//TODO: Ask for input
while (fgets(buffer, BUF_LEN, stdin) == NULL)
{
  //TODO: Check and handle error
}
buf_len = strlen(buffer);
//Remove trailing '\n', if present
if (buffer[buf_len - 1] == '\n')
{
  buffer[--buf_len] = '\0';
}

尽管这是比较容易的,我不喜欢这种第二种方法,因为的strlen 扫描串另一个时间来确定它的长度。在大多数情况下,这不是一个性能问题,我不去,因为我有我自己的心理问题。

Even though it's easier, I don't like this second method, because strlen scans the string another time to determine its length. In most cases, this is not a performance issue, I avoid it because I have my own mental issues.

这篇关于STRCMP功能不能正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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