【问题标题】:How to count words in a document assuming the text file has multiple spaces假设文本文件有多个空格,如何计算文档中的单词
【发布时间】:2015-02-26 01:11:44
【问题描述】:

目标基本上是重新创建wc。我需要计算单词、字符、非空白字符和换行符。我什么都有,除了我不知道如何使它工作的单词。

当我在这里搜索时,每个人都假设文档在单词之间没有多个空格。我必须测试的文档保证有多个空格,因此这种计算单词的方法不起作用。

#include <stdio.h>

int main (int argc, char* argv[]) {
  int Spaces;
  Spaces = 0;
  int NewLine;
  NewLine = 0;
  int Characters;
  Characters = -1;
  char* filename = argv[1];

  if (argc < 2) {
    printf("Usage: \n   wc <filename>\n");
  } else {
    printf("Filename is: %s\n", filename );
    FILE* infile;
    infile = fopen(filename, "r");

    char c;
    do {
      if (c == ' ') {
        Spaces = Spaces + 1;
      }
      if (c == '\n') {
        NewLine = NewLine + 1;
      }
      Characters = Characters + 1;
    } while ((c = fgetc(infile)) != EOF);

    printf("Total number of characters: %d\n", Characters);
    Characters = Characters - NewLine - Spaces;
    printf("Total number of non-whitespace characters: %d\n", Characters);
    printf("Total number of lines: %d\n", NewLine);
  }
  return 0; 
}

【问题讨论】:

  • 这并不能解决您所询问的问题,但您应该将do/while 循环更改为普通的while 循环并将c 更改为@987654328 @.
  • c 未初始化。 (以及更多)
  • 注意:char c; --> int c;EOF 与所有其他char 区分开来。
  • This 是我在另一个主题上提出的问题,但那里的代码可能被证明是有用的。

标签: c


【解决方案1】:

通常你使用一个布尔变量,通常命名为in_word,如果当前字符是空格,你设置为false,如果不是,设置为true。当(且仅当)字数从 true 更改为 false(反之亦然)时,您会增加字数。

【讨论】:

    【解决方案2】:

    将您的代码实现为具有两种状态:in-a-word 和 not-in-a-word。然后在状态之间转换时增加计数。

    我建议在从非单词转换为单词时增加字数(而不是从单词转换为非单词),因此不需要特殊处理在文件末尾。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多