在文本文件中的单词中出现相同的字母

时间:2013-11-29 07:13:30

标签: c

我需要一个C程序来获取文本文件中双字母的单词数

例如:

I SEE WHITE CLOUDS IN THE SKY WITH A COOL BREEZE BLOWING ACROSS

文本文件中的上述语句应返回

count = 4

因为SEE,COOL,BREEZE和ACROSS都包含2个字母。

这是我的代码:

#include <stdio.h>
const char FILE_NAME[] = "\\code.txt";
#include <stdlib.h> 

int main() {
int             count = 0;
FILE           *in_file;
int             ch;
in_file = fopen(FILE_NAME, "r");
if (in_file == NULL) {
printf("Cannot open %s\n", FILE_NAME);
exit(8);
}
 while (1) {
ch = fgetc(in_file);
if (ch == EOF)
break;
++count;
}
printf("Number of characters in %s is %d\n",
              FILE_NAME, count);
system("pause");
return (0);
}

1 个答案:

答案 0 :(得分:0)

你只需跟踪你读过的最后一个字符:然后与它进行比较,如果它们相等就增加计数器!

#include <stdio.h>
#include <stdlib.h>

const char FILE_NAME[] = "\\code.txt";

int main(int argc, char **argv) {
  int             count = 0;
  FILE           *in_file;
  int             ch;
  in_file = fopen(FILE_NAME, "r");
  if (in_file == NULL) {
    printf("Cannot open %s\n", FILE_NAME);
    exit(8);
  }
  char lastChar = 0x00;
  while (true) {
    ch = fgetc(in_file);
    if (ch == EOF){
      break;
    }else if(ch == lastChar){
      ++count;
    }
    lastChar = ch;
  }
  printf("Number of characters in %s is %d\n", FILE_NAME, count);
  system("pause");
  return (0);
}