【问题标题】:interactions with counters and file i/o与计数器和文件 i/o 的交互
【发布时间】:2016-10-12 00:52:04
【问题描述】:

我有一个程序应该计算一个字母在文本文件中出现的次数。

void file_histogram(char *filename)
{
  FILE *file1;
    file1 = fopen(filename, "r");
    int size = 26;
    int charCounters[size];
    char c;
    int i, j;

    if(file1 != NULL) {
        while(fscanf(file1, "%c", &c) == 1) {
            for(i = 0; i < size; ++i) {
                if(c == i + 97) {
                    charCounters[i]++;
                    break;
                }
            }
        }
    }
    for(j = 0; j < size; ++j)
        printf("%c: %d\n", j + 97, charCounters[j]);
    fclose(file1);

这似乎是在计算第一个字符两次,然后大约一半被正确计算,另一半似乎都达到最大值或溢出。这里到底发生了什么?

【问题讨论】:

  • 你如何确定 int size = 26?这应该是针对特定的“已知”文件还是任何文件?
  • a) 你从来没有将 charCounters 设置为全 0。b) 你为什么在那个文件读取部分还有一个 for 循环?
  • 该数组是针对字母表中的每个字母
  • 文件将只包含小写字母。我的想法是遍历每个字母并增加一个计数器。
  • 帮助了,谢谢!

标签: c io overflow


【解决方案1】:

第一个for() 循环的逻辑不正确。建议类似:

#include <ctype.h>
....
// initialize to all 0s
int charCounters[26] = {0};
....
while(fscanf(file1, "%c", &c) == 1) 
{
    if( isalpha(c) )
    {  // then alphabet a...z or A...Z
        // -'a' to get offset from lower case 'a'
        // to use as index into array
        charCounters[ tolower(c)-'a' ]++;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 2015-05-24
    • 2012-07-05
    • 1970-01-01
    相关资源
    最近更新 更多