计算文本文件中的所有字符出现次数

时间:2014-03-19 19:04:31

标签: c file for-loop while-loop

以下代码段用于计算输入文本后文件中遇到的所有符号,下一步是计算所有字符的出现次数(例如' a'遇到3次,&#39 ; b' 0次等)。然而,当我编译循环变为无限时,计数始终为0.我的问题是它是否可以修复或以其他方式重写。

char type, c, text[100]; counts[100];
int count=0, i;

while((type=getchar())!=EOF) {
    fputc(type, f); count++;
}

printf("Symbols found: %d", count-1);
rewind(f);

while(fscanf(f, "%s", &text)) {
    for (i = 0; i < strlen(text); i++) {
        counts[(text[i])]++;
        printf("The %d. character has %d occurrences.\n", i, counts[i]);
    }
}   

2 个答案:

答案 0 :(得分:0)

您可以在阅读输入时构建直方图。 getchar()的返回值为int,而不是char,因为除了EOF值之外,它还必须代表char。构建直方图后,您可以遍历存储桶并打印它们。在这里,我假设所有256个char值都是可能的,并包含以十六进制表示法显示不可打印字符的代码。

#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, char **argv)
{
    int c;
    int i;
    int histogram[256];
    int total;

    memset(histogram, 0, sizeof(histogram));
    total = 0;

    while ((c = getchar()) != EOF) {
        histogram[c]++;
        total++;
    }

    printf("Symbols found: %d\n", total);

    for (i = 0; i < 256; i++) {
        if (histogram[i]) {
            char repr[5];
            sprintf(repr, isprint(i) ? "%c" : "\\x%02x", i);
            printf("The '%s'. character has %d occurrences.\n", repr, histogram[i]);
        }
    }

    return 0;
}

答案 1 :(得分:0)

您的for循环扫描字符串,变量i是测试字符的索引,但您的printf表示i是符号。 您应该将计数和打印结果分开:

char * ptr;

while(fscanf(f, "%s", text))
   for (ptr = text; * ptr != 0; ptr++)
       counts[ (unsigned char)*ptr ]++;

for( i = 0; i < 256; i++)
    printf("The %d. character has %d occurrences.\n", i, counts[i]);

不要忘记声明count[ 256]并注意scanf获取text,而不是`&amp; text~作为目的地。

相关问题