Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert ifstream to istream

Tags:

c++

casting

How would one go about casting a ifstream into a istream. I figure since ifstream is a child of istream I should be able to do so but I have been 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;
.....
}
like image 810
Anonymous Avatar asked Nov 02 '10 17:11

Anonymous


People also ask

Can you pass an ifstream as an istream?

Note: Both cin and all the ifstream objects can be passed as a reference to istream . As you know, ifstream almost works the same as istream .

How do you define istream?

istream Class − The istream class handles the input stream in c++ programming language. These input stream objects are used to read and interpret the input as a sequence of characters. The cin handles the input. ostream class − The ostream class handles the output stream in c++ programming language.

Does ifstream create a file?

Bookmark this question.

What is the difference between ifstream and Fstream?

ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file. ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.


1 Answers

No cast is necessary.

#include <fstream>
int main()
{
    using namespace std;
    ifstream    f;
    istream&    s   = f;
}
like image 54
Cheers and hth. - Alf Avatar answered Sep 21 '22 11:09

Cheers and hth. - Alf