c - 尝试计算文件中的单词数

标签 c arrays function isspace

我有一个名为 myf 的文件其中有很多文本,我尝试使用空格作为计算字数的方法。基本上,在我的程序的 count 方法中,有一个变量 int d ,其作用类似于 bool 函数。另外,还有一个名为 count 的增量器.

我有一个for循环将遍历放入方法 count 的参数中的数组,并查看指针 *p 是否是一个非字母。如果是非字母 AND d=0 , d=1count是递增的。这样,如果下一个字符也是非空格,因为 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() 的结果因为它返回 intunsigned 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/

相关文章:

c - 数组中的邻居

创建将当前时间打印到命令行的 pthread

javascript - 如何动态地向对象添加数组?

function - 如何在 F# 中定义相互依赖的函数?

c++ - C++ 如何选择调用哪个重载函数?

c++ - 用于管理 C/C++ 嵌入式设备中的菜单的库

c - 如何在C程序中使用atan()函数求角度?

java - 如何将数组列表中的给定键与 HashMap 键进行比较?

c++ - OpenMP atomic 是否应用于行、变量名或实际内存地址?

typescript - typescript 中可选的必需参数