Im looking to create a vector that stores a list of different input streams including cin and a few text files. So far I have this.
vector<istream> inStreams;
vector<istream>::iterator streamsIterator;
streamsIterator = inStreams.begin();
streamsIterator = inStreams.insert(streamsIterator, cin); ////this has error!
for (char i = 1; argv[i] != NULL; i++) {
streamsIterator = inStreams.insert(streamsIterator, ifstream(argv[i], ifstream::in));
}
The problem is that the compiler spits out a big error that goes deep into the template library that I just cant decipher.
There are a few problems here. First is streams are not copyable so you can't copy them into a container. Although if you have a very recent compiler that supports it, streams are moveable.
However because you want to store different types in the one container that are polymorphic you can't even move them in. You can't store a std::fstream
in the space allocated to a std::istream
because you get slicing (corruption).
One way to do this is using pointers to store in your container:
int main(int, char* argv[])
{
std::vector<std::istream*> istreams;
istreams.push_back(&std::cin);
for(char** arg = argv + 1; *arg; ++arg)
{
istreams.push_back(new std::ifstream(*arg));
}
}
Unfortunately now you have a problem of ownership. The std::ifstream
objects you added that were created with new
need to be deleted but the global std::cin
object should not be deleted.
How you solve that problem depends on what you are trying to do overall but mixing pointers that need deleting with those that should not be deleted is problematic.