【发布时间】:2026-01-22 16:55:02
【问题描述】:
所以我有几个文本文件。我需要找出文件中最常见的 10 个字符和单词。我决定使用一个向量,并用文件中的每个字符加载它。但是,它需要包含空格和换行符。
这是我目前的功能
void readText(ifstream& in1, vector<char> & list, int & spaces, int & words)
{
//Fills the list vector with each individual character from the text ifle
in1.open("test1");
in1.seekg(0, ios::beg);
std::streampos fileSize = in1.tellg();
list.resize(fileSize);
string temp;
char ch;
while (in1.get(ch))
{
//calculates words
switch(ch)
{
case ' ':
spaces++;
words++;
break;
default:
break;
}
list.push_back(ch);
}
in1.close();
}
但由于某种原因,它似乎无法正确保存所有字符。我在程序的其他地方有另一个向量,它的 256 个整数全部设置为 0。它通过包含文本的向量,并在另一个向量中用它们的 0-256 int 值计算字符。但是,它可以很好地计算它们,但是空格和换行符会导致问题。有没有更有效的方法来做到这一点?
【问题讨论】:
标签: c++