抱歉,如果标题令人困惑。我有一个程序可以从文件中读取字符并记录每个 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/