Convert ifstream to istream

How could ifstream be translated into an istream stream. I believe that if the stream is a child of istream, I should do it, but I am having problems with such a task.

std::istream & inputStr = std::cin; std::ostream & outputStr = std::cout; if(argc == 3){ std::fstream inputFile; inputFile.open(argv[1], std::fstream::in); if(!inputFile){ std::cerr << "Error opening input file"; exit(1); } inputStr = inputFile; ..... } 
+7
c ++ casting
source share
3 answers

No rolls are required.

 #include <fstream> int main() { using namespace std; ifstream f; istream& s = f; } 
+20
source share

Try:

 std::ifstream* myStream; std::istream* myOtherStream = static_cast<std::istream*>(myStream); myOtherStream = myStream; // implicit cast since types are related. 

The same thing works if you have a link (&) to the stream type. static_cast is preferred in this case, since the cast is performed at compile time, allowing the compiler to report an error if translation is not possible (i.e. istream not a basic ifstream type).

In addition, and you probably already know this, you can pass an ifstream pointer / link to any function that accepts an istream pointer / link. For example, a language is resolved as follows:

 void processStream(const std::istream& stream); std::ifstream* myStream; processStream(*myStream); 
+1
source share
 std::istream *istreamObj = dynamic_cast<std::istream *>(&ifStreamObj) 
0
source share

All Articles