gpt4 book ai didi

计算文件中的字数?

转载 作者:太空宇宙 更新时间:2023-11-04 05:46:20 25 4
gpt4 key购买 nike

我有一个用 C 编写的程序,它应该计算单词“the”在作为参数给出的文本文件中出现的次数。但是该程序一直出现段错误,我不知道如何做解决这个问题。任何帮助将不胜感激。谢谢!

代码如下:


#include <stdio.h>
#include <string.h>
void main(int argc, char *argv[])
{
int h,i;
FILE *fp;
char* mess;
for(i=1; i < argc; i++)
{
h=0;
fp=fopen(argv[i],"r");
while (!feof(fp))
{
fscanf(fp,"%s",mess);
if (strcmp(mess,"the")==0)
h++;
}
printf("The file %s contains the word \"the\" %d times.",argv[i],h);
h=0;
fclose(fp);
}
}

最佳答案

 char* mess;
[...]
fscanf(fp,"%s",mess);

mess 未初始化。您需要为正在阅读的单词分配一些空间

s Matches a sequence of non-white-space characters; the next pointer must be a pointer to char, and the array must be large enough to accept all the sequence and the terminating NUL character. The input string stops at white space or at the maximum field width, whichever occurs first.

所以你还想使用字段宽度来限制你读取的内容到你的缓冲区的大小。这需要一些小心处理,因为缓冲区大小之后的位可能只是“the”(例如,“breathe”,如果你阅读 4 个字符的单词,会给你“brea”和“the”以及误报)

关于计算文件中的字数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4256002/

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