使用 C 计算文本文件中的单词数
嘿,我一直在尝试计算文本文件中的单词数,从 C 语言为 Hangman 游戏加载一堆单词,但我遇到了困难。我正在使用的这段代码假设我正在使用这段代码;
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;
工作!非常感谢!
Hey I have been trying to count the number of words in my text file, to load up a bunch of words for a Hangman game, from C but I am hitting a brick wall. This piece of code I am using is supposed I am using this piece of code;
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);
}
If anyone has anyone has any suggestions on how to fix this I would be very grateful.
The text file has 1 word per line, with 850 words.
Applied the buffer suggestion, however the word count still came out at 1606419282.
The correction of putting
int nwords = 0;
Worked!! Thank you very much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
那么这些词是每行一个条目吗?
不做你认为它做的事。它读取 nwords 中的字符串,但它不是字符串。
如果你想这样做,那么你需要分配一个字符串,即 char buffer[XXX] ,它足够长以包含数据文件中最长的留置权并使用:
So the words are one entry per line?
Doesn't do what you think it does. It reads a string in nwords, which isn't a string.
If you want to do it like this then you need to allocate a string ie
char buffer[XXX]
which is long enough to contain the longest lien in your data file and use:变量
nwords
从未被初始化。你不能假设它从零开始。如果是这样,你会在下一行发生崩溃(“除以零”),其目的使我无法理解:
所以,替换
为
The variable
nwords
is never initialized. You cannot assume it to start out as zero.If it were, you'd get a crash ("divide by zero") on the next line, whose purpose eludes me:
So, replace
by
更改建议:
fscanf(infile, "%s ", &buffer) // 注意空格!和&缓冲之前
它将丢弃所有空格,直到下一个单词。它应该可以工作。
PS 最好不要使用 [f]scanf :-)
Change proposed:
fscanf(infile, "%s ", &buffer) // notice the space!!! And & before buffer
It will throw off ALL whitespace till the next word. It should work.
P.S. Better not use [f]scanf :-)