c - strcmp 函数无法正常工作

标签 c string structure strcmp

我在结构数组 books 上有一个delete 函数。我向它传递了一组记录、书的作者书名 以及列表大小

现在这里 假设 list[0].authorlist[5].authorauthor 都等于“Dan Brown”(相同的字符串)

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
}    

为什么会这样?这里有什么问题吗?

最佳答案

来自 fgets 的文档:

Reading stops when a newline character is found, at end-of-file or error. The newline, if any, is retained.

这意味着 fgets不会从读取的字符串末尾删除最后的 '\n'。因此,您的字符串是:

  1. “丹·布朗”
  2. “丹·布朗”
  3. “丹·布朗\n”

它们相等。

这是使用 fgets 时非常常见的问题。这就是为什么我通常更喜欢 scanf,就像这样:

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 会再次扫描字符串以确定其长度。在大多数情况下,这不是性能问题,我避免它是因为我有自己的心理问题。

关于c - strcmp 函数无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19609328/

相关文章:

string - 在Flex/Bison中实现字符串插值

java - Java 中的字符串操作导致 "String index out of range"

structure - Bio.PDB如何识别异物残基?

c - scanf ("%[^\n]s")对于普通变量可以正常工作,但对于 C 中的结构变量不起作用

看不懂这个圆周率算法

c - %4d 用括号括起来有什么用?

regex - 提取逗号和引号之间的文本,忽略 perl 中的转义字符

c - 为什么父进程只读取子进程的第一条和第六条消息?

c - 在 C 中输出方程

c - 使用指针访问shm结构