【问题标题】:strncmp() gives a false positivestrncmp() 给出误报
【发布时间】:2013-10-15 22:13:29
【问题描述】:

我一直在解决 strncmp 和 getline 的问题......所以我做了一个小测试应用程序。 strncmp 给出误报,我无法弄清楚我做错了什么。

这是程序

#include <stdio.h>

FILE *fp=NULL;
char uname[4]="test";
char *confline=NULL;
size_t conflinelength=0;
int datlength;

main()
{
    datlength=4;
    fp=fopen("test.txt","r+");
    while (getline(&confline,&conflinelength,fp)!=-1)
    {
        if (strncmp(confline,uname,(datlength-1))==0);
        {
            printf("match\n");
            return;
        }
    }
    printf("no match\n");
    fclose(fp);
}

这是“test.txt”...

bjklas

程序输出

match

【问题讨论】:

  • char uname[4]="test"; 可以作为datlength=4,但建议使用char uname[]="test";printf("match\n"); 后面也应该跟 fclose(fp);

标签: c getline strncmp


【解决方案1】:
if (strncmp(confline,uname,(datlength-1))==0);
    printf("match\n");

等价于

if (strncmp(confline,uname,(datlength-1))==0)
    ;
printf("match\n");

您需要从if 行的末尾删除;

【讨论】:

    【解决方案2】:
    if (strncmp(confline,uname,(datlength-1))==0);
                                                 ^ roh-roh
    

    【讨论】:

      【解决方案3】:

      我猜这是您输入分号时的拼写错误;在 if 条件而不是其语句的末尾,即在曲线括号之后 }

      出于兴趣,我更喜欢使用 fgets,因为 getline 不在标准 C 库中

      【讨论】:

      • 你指的是 if (strncmp(confline,uname,(datlength-1))==0); 行吗?
      【解决方案4】:

      如果您使用char uname[5]="test";,此行将自动附加'\0',使其成为C 字符串,但只分配了4 个空格,它不能。相反,它是一个未终止的 char 数组...

      char uname[4]="test"; 产生一组未终止的字符,即不是 C 字符串。即“|t|e|s|t|”
      这将编译,但它不能被某些字符串函数(strcmp、strlen 等)处理,从而导致运行时错误。

      建议char uname[]="test"; 这将自动处理附加 NULL 终止符,产生一个 C 字符串:“|t|e|s|t|\0|”。此方法是初始化 char 数组的首选方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多