【问题标题】:Read contents of a text file character by character into a vector without skipping whitespace or new lines将文本文件的内容逐个字符读取到向量中,而不跳过空格或换行符
【发布时间】: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++


    【解决方案1】:

    您的代码现在的问题是您正在调用

    list.resize(fileSize);
    

    并使用

    list.push_back(ch);
    

    同时在您的读取循环中。你只需要一个或另一个。

    省略其中一个。


    有没有更有效的方法?

    最简单的方法是使用您已知的大小调整std::vector &lt;char&gt; 的大小,然后使用std::ifstream::read() 一次性读取整个文件。之后根据矢量内容计算其他所有内容。
    大致如下:

    list.resize(fileSize);
    in1.read(&list[0],fileSize);
    
    for(auto ch : list) {
        switch(ch) {
           // Process the characters ...
        }
    }
    

    【讨论】:

    • std::ifstream::read() 能否将字符直接推入vector?还是需要缓冲区作为中介?
    • @blackpen 它使用以前调整大小的向量作为缓冲区。与push_back()无关。
    • 谢谢。我究竟如何使用 read 将文件发送到向量?我还需要能够使用多个随机大小的文件
    • @ConnorSchwinghammer 我希望它现在更清楚了。不过,您始终可以参考第一名的reference documentation
    • @πάνταῥεῖ,好点子!我不知道是什么。此外,在 c++11 中,您似乎也可以执行 list.data()
    最近更新 更多