我正在阅读文件中的内容,我期待找到一个特定的值,比如说“伦敦”。 为此我正在阅读内容,用“ n”标记它,然后使用“strcmp”将每个值与“london”进行比较。
但我想我仍然不明白C如何存储数据并进行比较,因此下面的代码不能像我期望的那样工作。 我想我在这里缺少一些C的基础知识,请帮忙:
测试命令行:
./myprogram datafile.txt "london"
INPUT datafile.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] = ' '; } 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("equalsn"); //as expected, I get "equals" printed else printf("unequaln"); //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("%sn", st1); //this prints london, .... if(strcmp(st1,"london")==0) printf("equalsn"); //I was expecting this.. else printf("unequaln"); //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”的实际“字符串”?
非常感谢
我尝试以下的东西,并用strncpy
替换strcpy
的调用。 你最初的问题是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("%sn", st1); //this prints london, .... if(!strcmp(st1,"london")) printf("equalsn"); //I was expecting this.. else printf("unequaln"); //but i got this... entity = strtok(NULL, "n"); }
或者另一个解决方案是将’ 0’置于st1
的末尾,如下所示:
strcpy(st1, entity); st1[strlen(entity)-1] = ' ';
我测试了两者,它正在工作。
以上就是c/c++开发分享C从文件中读取字符串内容并比较相等相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/c-cdevelopment/519600.html