将文本文件的内容一个字符一个字符地读入矢量,不跳过空白或新行
Read contents of a text file character by character into a vector without skipping whitespace or new lines
所以我有几个文本文件。我需要找出文件中最常见的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值的字符。然而,它可以很好地计算它们,但是空格和换行会引起问题。有没有更有效的方法?
你的代码现在的问题是你正在调用
list.resize(fileSize);
和使用
list.push_back(ch);
同时出现在你的读循环中。你只需要其中之一。
省略其中一个
有更有效的方法吗?
最简单的方法是用您已经知道的大小调整std::vector <char>
的大小,并使用std::ifstream::read()
一次读取整个文件。然后从vector内容中计算所有内容。
下面的内容:
list.resize(fileSize);
in1.read(&list[0],fileSize);
for(auto ch : list) {
switch(ch) {
// Process the characters ...
}
}
相关文章:
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 使用动态分配将 char* 复制到另一个字符**
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何在不知道对应关系的情况下在字符串中搜索字符并将其分配给另一个字符?
- 如何检查一个字符是否与字符数组中的另一个字符匹配?
- C++:使用另一个字符将一个字符大写
- 我可以得到一个字符 * 到一个 std::sregex_iterator 匹配 str() 吗?
- 使用连续分隔符和空最后一个字符进行拆分
- 如何比较文件中包含的下一个字符
- 如何检查字符串中的最后一个字符是否是某个字符并将其从字符串中删除?(C++)
- 如何从文本文件中一次读取一个字符
- 将一个字符替换为字符串中更多数量的字符,而不删除C++中的其他字母
- 读取输入后,输出丢失了一个字符
- 比较最后一个字符,不区分大小写(带谓词?
- 如果一个字符,比如说"9",我减去"0",我在结果上使用 is 数字,我是真还是假
- 为什么 std::istream::gcount 返回的字符比预期的多一个字符
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 使用 char 将一个字符数组分配给另一个字符数组时出现奇怪的行为
- 在弦乐器中删除最后一个字符