c++ - 使用多个 ifstreams 作为 ifstreams 的 vector

标签 c++ vector shared-ptr fstream ifstream

我正在尝试逐行读取多个文件(本例中为 3 个)并使用 ifstream shared_ptrs vector 来执行此操作。但我不知道如何取消引用此指针以使用 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

    }
}

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

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

关于c++ - 使用多个 ifstreams 作为 ifstreams 的 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58749629/

相关文章:

c++ - 为什么我的代码从来没有得到命令重启?

c++ - 动态描述数学规则

vector - Rust中的Vec <(i64,i64)>数据类型是什么?

c++ - C++:遍历字符串 vector 并将索引用于putenv

c++ - 将 shared_ptr<T> 转换为 shared_ptr<void>

c++ - 下一个词法 "permutation"算法

c++ - 来自嵌套列表的成员,如何调用外部数据

python - 使用gensim的Doc2Vec生成句子向量

c++ - boost 共享指针构造函数析构函数

c++ - 如何通过共享 ptr 访问类的成员函数到共享 ptr?