将文本文件的内容一个字符一个字符地读入矢量,不跳过空白或新行

Read contents of a text file character by character into a vector without skipping whitespace or new lines

本文关键字:一个 字符 新行 空白 文件 文本      更新时间:2023-10-16

所以我有几个文本文件。我需要找出文件中最常见的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 ...
    }
}
相关文章: