【问题标题】:Working with multiple ifstreams as a vector of ifstreams使用多个 ifstream 作为 ifstream 的向量
【发布时间】:2019-11-07 13:20:19
【问题描述】:

我正在尝试逐行读取多个文件(本例中为 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

    }

【问题讨论】:

  • 如果f 是一个指向std::ifstream 的普通指针,你会怎么做?你会以完全相同的方式来做,在这里。假设std::shared_ptr 是一个指针。
  • 顺便说一句,不需要经历 i - '0' - 1 的所有舞蹈 - 只需使用 for (auto i = 0; i &lt; 3; ++i) 或(更好)基于范围的 for (auto f: files)
  • 如果您还在学习,添加一些明确的名称会很有帮助,例如ifstream&amp; ref = *f(为取消引用智能指针的结果定义名称/引用)。

标签: c++ vector shared-ptr fstream ifstream


【解决方案1】:

取消引用 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

    }
}

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

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

【讨论】:

  • 感谢您的帮助。我会记住你的笔记以备将来使用:)
猜你喜欢
  • 1970-01-01
  • 2014-07-28
  • 1970-01-01
  • 1970-01-01
  • 2011-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
相关资源
最近更新 更多