gpt4 book ai didi

C从文件中读取字符串内容并比较相等性

转载 作者:行者123 更新时间:2023-11-30 17:12:36 25 4
gpt4 key购买 nike

我正在从文件中读取内容,并且希望查找特定值,例如“伦敦”。为此,我正在阅读内容,用“\n”对其进行标记,然后使用“strcmp”将每个值与“伦敦”进行比较。

但我认为我仍然不明白 C 如何存储数据并进行比较,因此下面的代码无法按我的预期工作。我想我在这里缺少一些 C 的基础知识,请帮助:

测试命令行:

./myprogram datafile.txt "london"

输入数据文件.txt:

london
manchester
britain
...

代码myprogram.c:

int main(int argc, char **argv) {
FILE* fl;
char st1[2000];
char * buffer = 0;
long length;

fl = fopen (argv[1], "r"); //the data file content is shown above
if (fl){
fseek (fl, 0, SEEK_END);
length = ftell (fl);
fseek (fl, 0, SEEK_SET);
buffer = malloc (length+1);
if (buffer){
//fread (buffer, 1, length, fl);
fread(buffer, sizeof(char), length, fl);
buffer[length] = '\0';
}
fclose (fl);
}else{
printf("data file not found");
return -1;
}


//firstly let's compare the value passed by command line with "london"
strcpy(st1, argv[2]);
if(strcmp(st1,"london")==0)
printf("equals\n"); //as expected, I get "equals" printed
else
printf("unequal\n");


//now let's compare the values extracted from the data file,
char* entity = strtok(buffer, "\n");
while (entity != NULL) {
strcpy(st1, entity); //copy the value from the char pointer entity to the char array st1 so we can compare with other strings

printf("%s\n", st1); //this prints london, ....

if(strcmp(st1,"london")==0)
printf("equals\n"); //I was expecting this..
else
printf("unequal\n"); //but i got this...
entity = strtok(NULL, "\n");
}
return 0;

}

我期望上述程序的输出为:

equals
london
equals
manchester
unequal
britain
unequal
...

但我不明白为什么我会这样

equals
london
unequal <=============== why and how to fix?
manchester
unequal
britain
unequal
...

我应该如何更改它,以便从文件中读取的值“london”等于“london”的实际“字符串”?

非常感谢

最佳答案

我尝试了以下操作,并将 strcpy 的调用替换为 strncpy。您最初的问题是 st1 变量末尾的“\0”。所以你可以这样做:

  while (entity != NULL) {
strncpy(st1, entity,strlen(entity)-1); //copy the value from the char pointer entity to the char array st1 so we can compare with other strings

printf("%s\n", st1); //this prints london, ....

if(!strcmp(st1,"london"))
printf("equals\n"); //I was expecting this..
else
printf("unequal\n"); //but i got this...
entity = strtok(NULL, "\n");
}

或者另一种解决方案是将“\0”自己放在st1的末尾,如下所示:

strcpy(st1, entity);
st1[strlen(entity)-1] = '\0';

我测试了两者并且它有效。

关于C从文件中读取字符串内容并比较相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31430884/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com