c++ - 计算文件中字符出现的频率。 C++

标签 c++ character frequency

任务是使用频率表(不区分大小写字母)将(给定文本文件)遇到的拉丁字符打印到文件f1。该表必须按字母顺序排序。 到目前为止,我的程序只计算字母 A。我在创建遍历整个字母表并将表格打印到另一个文件的循环时遇到问题,你能帮我解决这些问题吗?

#include <stdio.h>
const char FILE_NAME[] = "yo.txt";
#include <stdlib.h> 
#include <iostream>
using namespace std;
int main() {
    int   count = 0;  /* number of characters seen */
    FILE  *in_file;    /* input file */

    /* character or EOF flag from input */
    int             ch;

    in_file = fopen(FILE_NAME, "r");
    if (in_file == NULL) {
        printf("Cannot open %s\n", FILE_NAME);
        system("Pause");
        exit(8);
    }

    while (1) {
        char cMyCharacter = 'A';
        int value = (int)cMyCharacter;
        ch = fgetc(in_file);
        if (ch == EOF){
            break;
        }
        int file_character = (int) ch;
        if (file_character == value || file_character == value+ 32) {
             count++;
        }
    }

    printf("Number of characters in %s is %d\n", FILE_NAME, count);
    char cMyCharacter = 'A';
    int iMyAsciiValue = (int)cMyCharacter;
    cout << iMyAsciiValue;
    system("Pause");
    fclose(in_file);

    return 1;
}

最佳答案

首先,为 a 到 z 的频率获取一个大小为 26 的数组

int freq[26] = {0};

freq[0] 用于“a”,freq[1] 用于“b”,等等。

二、改变

if (file_character == value || file_character == value+ 32)

if (file_character >= 'a' && file_character <= 'z')

对于所有小写字母(即“a”到“z”)。

三、获取索引并计数

freq[file_character - 'a']++;

, file_character - 'a' 计算索引,其余的算在内。

第四,打印freq数组。

五、添加

else if (file_character >= 'A' && file_character <= 'Z')

对于大写字符,并相应地更改后续代码。

这是你的作业,你应该尝试自己弄清楚整个程序。我希望这个答案能为您提供足够的提示。

关于c++ - 计算文件中字符出现的频率。 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13553140/

相关文章:

android - 在 Android SDK 中选择 Wifi Direct channel /频段?

c++ - 我想为每个组合框选择分配整数值并将它们集中打印在文本文件中

c++ - 如何结合模板偏特化和模板参数推导

C++ 类 - 如何将函数传递给包含的类以供其使用?

java - 用不同的字符替换字符串中的所有字符

c++ - 计算整数 vector 的频率分布

C++:从子类访问父类

MySQL和波兰语

javascript - 替换数组中的字符

android - 在android中播放立体声