使用C从文本文件中计算字数
嘿,我一直在努力计算我的文本文件中的单词数,为一个来自C的刽子手游戏加载一堆单词,但我遇到了麻烦。我正在使用的这段代码是假设我正在使用这段代码使用C从文本文件中计算字数,c,words,counting,C,Words,Counting,嘿,我一直在努力计算我的文本文件中的单词数,为一个来自C的刽子手游戏加载一堆单词,但我遇到了麻烦。我正在使用的这段代码是假设我正在使用这段代码 FILE *infile; FILE *infile; char buffer[MAXWORD]; int iwant, nwords; iwant = rand() %nwords; // Open the file infile = fopen("words.txt", "r"); // If the file cannot
FILE *infile;
FILE *infile;
char buffer[MAXWORD];
int iwant, nwords;
iwant = rand() %nwords;
// Open the file
infile = fopen("words.txt", "r");
// If the file cannot be opened
if (infile ==NULL) {
printf("The file can not be opened!\n");
exit(1);
}
// The Word count
while (fscanf(infile, "%s", buffer) == 1) {
++nwords;
}
printf("There are %i words. \n", nwords);
fclose(infile);
}
如果有人对如何解决这个问题有任何建议,我将不胜感激
文本文件每行有1个单词,共850个单词
应用缓冲区建议,但是字数仍然为1606419282
推杆的校正
int nwords = 0;
成功了!!多谢各位 那么每行只有一个条目
while (fscanf(infile, "%s", &nwords) == 1); {
++nwords;
}
不会做你认为它会做的事。它读取nwords中的字符串,而不是字符串。
如果要这样做,则需要分配一个字符串,即char buffer[XXX]
,该字符串足够长,可以包含数据文件中最长的留置权,并使用:
while (fscanf(infile, "%s", buffer) == 1) {
++nwords;
}
那么单词是每行一个条目
while (fscanf(infile, "%s", &nwords) == 1); {
++nwords;
}
不会做你认为它会做的事。它读取nwords中的字符串,而不是字符串。
如果要这样做,则需要分配一个字符串,即char buffer[XXX]
,该字符串足够长,可以包含数据文件中最长的留置权,并使用:
while (fscanf(infile, "%s", buffer) == 1) {
++nwords;
}
变量
nwords
从未初始化。你不能假设它一开始是零
如果是这样的话,你会在下一行遇到崩溃(“除以零”),我想不出它的目的是什么:
iwant = rand() %nwords;
那么,替换
int iwant, nwords;
iwant = rand() %nwords;
借
变量
nwords
从未初始化。你不能假设它一开始是零
如果是这样的话,你会在下一行遇到崩溃(“除以零”),我想不出它的目的是什么:
iwant = rand() %nwords;
那么,替换
int iwant, nwords;
iwant = rand() %nwords;
借
请注意,最好不要使用[f]scanf:-)
另外,最好不要使用[f]scanf:-)不是答案,但请看@MartinBeckett Hah,今天也在reddit上看到了,嗯?@Rooke news.ycombinator.com昨天!没有答案-但是看看@MartinBeckett Hah,今天也在reddit上看到了,嗯?@Rooke news.ycombinator.com昨天!当@cnicutar发现“;”时在循环中的“{”之前表示循环只运行过一次。正如@cnicutar发现的,“;”在循环中的“{”之前表示循环只运行过一次。