I am trying to read multiple files (3 in this example) line by line and using a vector of ifstream shared_ptrs to do this. But I do not know how to dereference this pointer to use getline() or there's some other error in my code.
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
}
Dereferencing a shared_ptr is very much like dereferencing a raw pointer:
#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
}
}
I have corrected the code so that it compiles, but have not addressed style issues as they aren't relevant to the question.
Note: it's easier for the community if you can post a complete minimal program rather than a snippet.