繁体   English   中英

使用多个 ifstream 作为 ifstream 的向量

[英]Working with multiple ifstreams as a vector of ifstreams

我正在尝试逐行读取多个文件(在此示例中为 3 个)并使用 ifstream shared_ptrs 的向量来执行此操作。 但我不知道如何取消引用该指针以使用 getline() 或我的代码中存在其他错误。

vector<shared_ptr<ifstream>> files;

for (char i = '1'; i < '4'; i++) {
        ifstream file(i + ".txt");
        files.emplace_back(make_shared<ifstream>(file));
    }

for (char i = '1'; i < '4'; i++) {
        shared_ptr<ifstream> f = files.at(i - '0' - 1); 
        string line;
        getline(??????, line); //What should I do here?

        // do stuff to line

    }

取消引用 shared_ptr 非常类似于取消引用原始指针:

#include <vector>
#include <fstream>
#include <memory>

int main()
{
    std::vector<std::shared_ptr<std::ifstream>> files;

    for (char i = '1'; i < '4'; i++) {
            std::string file = std::string(1, i) + ".txt";
            files.emplace_back(std::make_shared<std::ifstream>(file));
        }

    for (char i = '1'; i < '4'; i++) {
        std::shared_ptr<std::ifstream> f = files.at(i - '0' - 1); 
        std::string line;
        getline(*f, line); //What should I do here? This.

        // do stuff to line

    }
}

我已经更正了代码以便编译,但没有解决样式问题,因为它们与问题无关。

注意:如果您可以发布完整的最小程序而不是片段,那么对于社区来说会更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM