C++:输出文件中ASCII字符频率计数结果时出现奇怪的数字

标签 c++ ascii

抱歉,如果标题令人困惑。我有一个程序可以从文件中读取字符并记录每个 ASCII 字符出现的频率。最后,程序应该输出每个使用的 ASCII 字符及其使用次数(计数器)。

这是我的代码,可以正常编译和运行(请注意,注释掉的代码只是我以前使用过但不起作用的代码;我将其保留在那里以供引用):

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <iomanip>
using namespace std;

int main(void)
{
    ifstream inputFile;
    string infile;
    char ch;
    int i;
    int asciiArray[128] = {0};

    // Gets input filename from user, checks to make sure it can be opened, and then
    // gets output filename from user.
    cout << "Please enter your input filename: ";
    cin >> infile;

    inputFile.open(infile.c_str());

    if (inputFile.fail())
    {
        cout << "Input file could not be opened. Try again." << endl;
        exit(0);
    }

    // Gets the first character of the input file.
    //inputFile.get(ch);

    // Sets up the ASCII/Frequency table
    cout << left << setw(10) << "ASCII" << right << setw(10) << "Frequency" << endl;

    while(inputFile >> ch)
    {
        asciiArray[(int)ch]++;

        for (i = 0; i < 129; i++)
        {
            if (asciiArray[i] > 0)
            {
                cout << left << setw(10) << asciiArray[i] << right << setw(10) << asciiArray[(int)ch] << endl;
            }
        }
    }

    /*
    while(!inputFile.eof())
    {
        asciiArray[(int)ch]++;
        //cout << asciiArray[(int)ch] << endl;

        for (i = 0; i < 129; i++)
        {
            if (asciiArray[i] > 0)
            {
                cout << left << setw(10) << asciiArray[i] << right << setw(10) << asciiArray[(int)ch] << endl;
            }
        }

        inputFile.get(ch);
    }
    */

    // Closes the input file
    inputFile.close();

    return 0;
}

使用包含以下内容的文件运行程序时:

111
[newline added by text editor]

我得到以下输出:http://puu.sh/7jbnl.png

我有点迷茫,不确定那些随机的长数字是从哪里来的。我有一种感觉,也许我将 for 循环放在了错误的位置,因为在谈到循环时我往往会混淆。但除此之外,我很困惑。

注意:我今天早些时候问了一个关于这个程序的问题 (C++: Counting the frequency of ASCII characters in file),但它是关于实现计数器本身的(我相信我已经弄明白了)。

最佳答案

你的循环边界是错误的。

    for (i = 0; i < 129; i++)

应该是:

    for (i = 0; i < 128; i++)

您正在访问数组范围之外的 asciiArray[128],从而导致未定义的行为。它正在读取一些您未初始化为 0 的无关内存。

您还应该在阅读完文件后将该循环移至。您在读取每个字符后打印所有频率。

关于C++:输出文件中ASCII字符频率计数结果时出现奇怪的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22184848/

相关文章:

c++ - 获取有关硬盘扇区原始数据更改的通知 - 文件更改通知

c++ - 发生泄漏检查错误时如何使cuda-memcheck返回非零

ruby - 如何在 Ruby 中打印转义字符?

Python:使用for循环输出ASCII表

c - 程序发出蜂鸣声,即使它不包含\a 任何地方

c++ - 从自身内部替换 std::function(通过 move 赋值到 *this?)

C++ Placement new 和构造函数调用

c++ - 如何使深度中的对象易于配置 "from the top"?

c++ - 什么时候可以安全使用 `isalpha()`

c# - 我如何 "ASCII armor"我的 MemoryStream?