oddRaven oddRaven - 4 months ago 49
C++ Question

How to assign istringstream and ifstream to an istream variable?

I want to have a variable of type

istream
which can hold either the contents of a file or a string. The idea is that if no file was specified, the variable of type
istream
would be assigned with a string.

std::ifstream file(this->_path)


and

std::istringstream iss(stringSomething);


to

std::istream is


I've tried just assigning them to the
istream
variable like I would with other objects that inherit from the same base class, but that didn't work.

How to assign
istringstream
and
ifstream
to an
istream
variable?

Answer

Base class pointers can point to derived class data. std::istringstream and std::ifstream both derived from std::istream, so we can do:

//Note that std::unique_ptr is better that raw pointers
std::unique_ptr<std::istream> stream;

//stream holds a file stream
stream = std::make_unique<std::ifstream>(std::ifstream{ this->_path });

//stream holds a string
stream = std::make_unique<std::istringstream>(std::istringstream{});

Now you just have to extract the content using

std::string s;
(*stream) >> s;