strcmp功能无法正常工作

时间:2013-10-26 16:56:48

标签: c string structure strcmp

我在结构数组delete 上有 books函数。我正在传递一系列记录,author of bookname of book以及size of the list

现在鉴于list[0].authorlist[5].author以及author都等于“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
}    

为什么会这样?这有什么不对?

3 个答案:

答案 0 :(得分:2)

来自fgets的文档:

  

在找到换行符时,在文件结尾或错误时停止读取。 保留换行符(如果有)。

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

  1. “Dan Brown”
  2. “Dan Brown”
  3. “Dan Brown \ n”
  4. 他们相等。

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

答案 1 :(得分:1)

您应该验证您的输入。有时需要多种方法。在这里,我使用strlen()strstr(),因为如果长度为==,并且存在子串,那么字符串 ARE 相等。所以,在做出结论之前,尝试这样的方法来验证输入字符串是你的意思:

注意: 枚举当然不是必需的,但包含在此处是为了增加输出示例的清晰度。

enum    {
    SAME,     //0
    NOT_SAME  //1
}

void delete(struct books *list,char author[],char name[],int n)
{
    int i,a, len1, len2;
    A = NOT_SAME;
    len1 = strlen(list[0].author);
    len2 = (list[5].author);
    if(strstr(list[0].author,list[5].author) && (len1==len2)) a = SAME;
    printf("%d\n",a);              


    a = NOT_SAME;
    len1 = strlen(list[0].author);
    len2 = (author);
    if(strstr(list[0].author,author) && (len1==len2)) a = SAME;
    printf("%d\n",a);              

}    

答案 2 :(得分:0)

通过逐字符打印来检查第二个字符串。

特别是author字符串。

for(i=0; i < strlen(list[0].author);i++)
{
   if(list[0].author[i]!=author[i])
   {
     printf("this is position is not matching\n",i+1);
     //try to print characters and also print ascii characters.
     break; 
   }

}
//or simply try to use strncpy()