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