繁体   English   中英

使用C从一个文本文件计算单词数

[英]Counting the number of words using C from a text file

嘿,我一直在尝试计算文本文件中的单词数,以便从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; 

工作了! 非常感谢你!

那么单词是每行一个条目吗?

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;

通过

int nwords = 0;
  1. 读取第一个单词和其后的空白后,fscanf返回以输入缓冲空白。 因此,下一次您阅读“空”字。
  2. 建议更改:

    fscanf(infile,“%s”,&buffer)//注意空格! 和&之前的缓冲区

    它将放弃所有空格,直到下一个单词。 它应该工作。


PS最好不要使用[f] scanf :-)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM