我有一个名为 myf
的文件其中有很多文本,我尝试使用空格作为计算字数的方法。基本上,在我的程序的 count 方法中,有一个变量 int d ,其作用类似于 bool 函数。另外,还有一个名为 count
的增量器.
我有一个for
循环将遍历放入方法 count 的参数中的数组,并查看指针 *p
是否是一个非字母。如果是非字母 AND d=0
, d=1
和count
是递增的。这样,如果下一个字符也是非空格,因为 d=1
,else if 语句不会再次递增。 d 重置为 0 的唯一方法是如果存在空格,此时,如果找到另一个字母,它将再次递增。然后 count 方法将返回变量 count。看起来很简单,但我总是得到错误的数字。
#include <stdio.h>
#include<stdlib.h>
#include <string.h>
#include <ctype.h>
int count(char x[]) {
int d = 0;
int count = 0;
for (char *p = x; *p != EOF; *p++) {
// this will traverse file
printf("%c", *p);
// this is just to see the output of the file
if (*p == ' ' && d == 1) {
d = 0;
}
else if (*p != ' ' && d == 0) {
count++;
d = 1;
}
}
return count;
}
int main() {
char c;
int r = 0;
char l[1000];
FILE *fp = fopen("myf", "r");
while ((c = fgetc(fp)) != EOF) {
l[r] = c;
r++;
}
printf("\n %d", count(l));
}
最佳答案
要计算单词数,请计算非字母后字母的出现次数。
*p != EOF
是错误的测试。 EOF
指示输入操作 1) 没有更多输入或 2) 发生输入错误。它不表示字符串的结尾。
使用int
保存 fgetc()
的结果因为它返回 int
在unsigned char
范围内和EOF
。通常有 257 个不同的值。 char
还不够。
小东西:不需要数组。让代码考虑'
作为一封信。由于单词数量可能非常大,因此让代码使用宽类型,例如 unsigned long long
.
#include <ctype.h>
int isletter(int ch) {
return isalpha(c) || c == '\'';
}
#include <stdio.h>
int main(void) {
unsigned long long count = 0;
FILE *fp = fopen("myf", "r");
if (fp) {
int c;
int previous = ' ';
while ((c = fgetc(fp)) != EOF) {
if (!isletter(previous) && isletter(ch)) count++;
previous = ch;
}
fclose(fp);
}
printf("%llu\n", count);
}
关于c - 尝试计算文件中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36992128/