【问题标题】:Count all character occurrences in a text file计算文本文件中出现的所有字符
【发布时间】:2014-04-26 06:47:45
【问题描述】:

以下代码 sn-p 旨在计算输入文本后文件中遇到的所有符号,下一步是计算所有字符的出现次数(例如 'a' 遇到 3 次,'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]);
    }
}   

【问题讨论】:

  • 你在哪里设置size
  • 为什么不计算第一个getchar()循环中的字符数?
  • 谢谢,酒保。已编辑。
  • 字符代码大于 100。
  • 您不应该在将它们相加的同一循环中打印计数。您需要先将所有计数相加,然后再循环打印每个字符的计数。

标签: c file for-loop while-loop


【解决方案1】:

您可以在阅读输入时构建直方图。 getchar() 的返回值是 int,而不是 char,因为除了 256 个 char 值之外,它还必须表示 EOF。构建直方图后,您可以遍历存储桶并打印它们。在这里,我假设所有 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;
}

【讨论】:

    【解决方案2】:

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

    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,而不是`&text~作为目的地。

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 2017-06-18
      • 2010-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      相关资源
      最近更新 更多