gpt4 book ai didi

c - 文本文件中的单词中相同字母的出现次数

转载 作者:行者123 更新时间:2023-11-30 21:40:20 27 4
gpt4 key购买 nike

我需要一个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);
}

最佳答案

您只需跟踪您读入的最后一个字符:然后与其进行比较,如果相等,则增加计数器!

#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);
}

关于c - 文本文件中的单词中相同字母的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20280248/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com