为什么我的C程序中文本文件的字数不正确?

wz1wpwve  于 2023-08-03  发布在  其他
关注(0)|答案(1)|浏览(117)

我在数文件的字数。我写了下面的代码:

  1. while ((ch = fgetc(fptr)) != EOF)
  2. {
  3. if (ch == ' ' || ch == '\n' || ch == '\t' || ch == '\0')
  4. {
  5. no_of_words = no_of_words + 1;
  6. }
  7. }

字符串
对于一个包含以下内容的文本文件,它会将字数打印为8,而我期望的是6

  1. Hi, we are here.
  2. huio klhi

t30tvxxf

t30tvxxf1#

因为当ch是一个换行符(\n)时,no_of_words也是向上计数的,所以文本文件中的两个额外的换行符也被算作新词。
你可以做的是用另一个变量来跟踪你当前是否在一个单词中。每开始一个单词,就把它数一遍;但是当你在空白区域时不要计数:

  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. int main(void) {
  4. int ch;
  5. bool in_word = false;
  6. int no_of_words = 0;
  7. FILE *fptr = fopen("example.txt", "r");
  8. while ((ch = fgetc(fptr)) != EOF)
  9. {
  10. if (ch == ' ' || ch == '\n' || ch == '\t')
  11. {
  12. in_word = false;
  13. } else
  14. if (!in_word)
  15. {
  16. in_word = true;
  17. no_of_words = no_of_words + 1;
  18. }
  19. }
  20. fclose(fptr);
  21. printf("words: %d\n", no_of_words);
  22. return 0;
  23. }

字符串
此外,不需要检查ch是否为\0(0),因为从fgetc接收的最后一个值将是EOF(通常定义为-1)。由于ch可以接收超过256个不同的值,因此必须使用int类型进行定义。

展开查看全部

相关问题