C++ Piping ifstream into stringstream

scx picture scx · Dec 13, 2014 · Viewed 7.9k times · Source

I am overloading my istream operator, so I can replace std::cin with my object. I know I will have to feed it an empty stringstream for the final output to work.

I would like to feed an std::ifstream into a std::stringstream as so:

while(ifs >> ss) {}

Is this possible? Here is an example prototype code:

friend istream & operator >> (istream & is, Database & db)
{
    ifstream ifs;
    ifs.open(db.inputFilename_, ios::in | ios::binary);
    if (!ifs.is_open())
    {
        cout << "Couldn't read " << db.inputFilename_ << endl;
        return is;
    }
    while (ifs >> db.iss)
    {}
    ifs.close()
    return db.iss;
}

I am not interested in any answers that start with "use Boost" :) This is a purely standard C++ project. Thank you for any help or pointers.

Right now I am getting:

error: invalid operands to binary expression ('ifstream' (aka 'basic_ifstream<char>') and 'istringstream' (aka 'basic_istringstream<char>'))

Answer

NaCl picture NaCl · Dec 13, 2014

Simply do this:

 if(ifs){
     db.iss << ifs.rdbuf();    
     ifs.close();
 }