Strcmp没有返回0

时间:2016-01-21 02:09:56

标签: c string file parsing

我有一个看起来像这样的文本文件:

TEMP:88
TT:33
3d;3d:5

我正在尝试解析第一行,并检查它确实是“TEMP:88”

这就是我的尝试:

FILE * file = fopen("test.txt","r");

if(file == NULL)
    exit(0);
char buff[128];

while(fgets(buff,sizeof(buff),file) != NULL) {
     if(strcmp(buff,"TEMP:88") == 0) 
         printf("TRUE");
     else
         printf("FALSE"); //prints false, regardless of newline character, use of memcopy or anything else
     break;
}

然后我尝试在strcmp中添加新行字符“\ n”,产生相同的结果,mem copy也产生了相同的结果,任何想法?

2 个答案:

答案 0 :(得分:0)

来自以下源代码

FILE * file = fopen("test.txt","r");
if(file == NULL)
    exit(0);
char buff[128];

while(fgets(buff,sizeof(buff),file) != NULL) {
    printf("%s,%d\n",buff,strlen(buff));
    int i= 0;
    while(i<strlen(buff))
    {
        printf("%d\n",buff[i]);
        i++;
    }
    if(strcmp(buff,"TEMP:88") == 0) 
        printf("TRUE");
    else
        printf("FALSE"); //prints false, regardless of newline character, use of memcopy or anything else
    break;
}

它的输出是,

  

$ ./a.exe TEMP:88,9 84 69 77 80 58 56 56 13 10 FALSE

此ASCII值和字符串长度显示您的读取字符串不是&#34; TEMP:88&#34;。 读缓冲区最后包含LF和CR的ASCII值。

所以你可以使用

strncmp(buff,"TEMP:88",strlen("TEMP:88"));

答案 1 :(得分:-1)

只是为了补充上述评论之一,引用以下链接:

http://www.cplusplus.com/reference/cstdio/fgets/

  

换行符使fgets停止读取,但它被认为是a   函数的有效字符并包含在复制到的字符串中   海峡

所以是的,您应该在比较中包含\ n

相关问题