我有一个如下所示的文本文件:
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 也产生了相同的结果,有什么想法吗?
最佳答案
来自下面的源代码
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 值和字符串长度表明您读取的字符串不是“TEMP:88”。 读取缓冲区末尾包含 LF 和 CR 的 ASCII 值。
所以你可以使用
strncmp(buff,"TEMP:88",strlen("TEMP:88"));
关于c - Strcmp 不返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34914192/