我正在尝试编写一个程序来打印文本文件中找到的单词数。单词被定义为由任意数量的空格分隔的字符序列。
但是,当存在多个空格时我会遇到问题,因为它不会报告正确的单词数。
这是迄今为止我的代码:
#include <stdio.h>
int main()
{
FILE *fp;
char str;
int i=0;
/* opening file for reading */
fp = fopen("myfile.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
while(( str = fgetc(fp)) != EOF ) {
if (str == ' ')
++i;
}
printf("%d\n", i);
fclose(fp);
return(0);
}
myfile.txt 是:
Let's do this! You can do it. Believe in yourself.
我不确定是否使用 fgets、fscanf 或 fgetc。
假设我定义了空格,就像读取字符串时在 fscanf 函数中定义的那样
它打印的 14 是不正确的。我不确定如何解释多个空格。在这种情况下,空格是单词之间任意数量的空格。
最佳答案
仅当空格前面没有任何其他空格时才计算空格即可。
#include <stdio.h>
int main()
{
FILE *fp;
char str;
char prevchar; //tracks the previous character
int i=0;
/* opening file for reading */
fp = fopen("myfile.txt" , "r");
if(fp == NULL) {
perror("Error opening file");
return(-1);
}
prevchar='x'; //initialize prevchar to anything except a space
while(( str = fgetc(fp)) != EOF ) {
if (str == ' ' && prevchar!=' ') // update the count only if previous character encountered was not a space
++i;
prevchar=str;
}
printf("%d\n", i+1);
fclose(fp);
return(0);
}
编辑:代码假设单词由一个或多个空格分隔,并且不涵盖所有极端情况,例如句子分布在多行上或单词由逗号而不是空格分隔时。但这些情况可以通过添加更多条件来涵盖。
关于计算具有多个空格的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22246723/