计算文件中字符的频率。 C ++

时间:2012-11-25 16:47:57

标签: 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;
}

1 个答案:

答案 0 :(得分:2)

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

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')

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

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