我试图逐行读取多个文件(在本例中为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
}发布于 2019-11-07 21:58:10
取消引用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
}
}我已经更正了代码,以便它可以编译,但没有解决样式问题,因为它们与问题无关。
注意:如果你能发布一个完整的最小程序而不是一小段代码,对社区来说会更容易。
https://stackoverflow.com/questions/58749629
复制相似问题