简体   繁体   English

C ++将ifstream管道化为stringstream

[英]C++ Piping ifstream into stringstream

I am overloading my istream operator, so I can replace std::cin with my object. 我正在重载我的istream运算符,所以我可以用我的对象替换std::cin 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: 我想将std::ifstreamstd::stringstream如下所示:

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. 我对以“使用Boost”开头的任何答案都不感兴趣:)这是一个纯粹的标准C ++项目。 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>'))

Simply do this: 只需这样做:

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

You can use std::copy with an std::istream_iterator for std::cin and std::ostream_iterator for the std::stringstream . 您可以将std::copystd::istream_iterator用于std::cin ,将std::ostream_iterator用于std::stringstream

#include <algorithm>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>

void redirect(std::ifstream &is, std::stringstream &os) {
    is >> std::noskipws;
    std::istream_iterator<char> begin(is);
    std::istream_iterator<char> end;
    std::ostream_iterator<char> out(os);
    std::copy(begin, end, out);
}

Note that this copies the entire file into the std::stringstream , and thus for really large files that can't fit in memory, this will fail. 请注意,这会将整个文件复制到std::stringstream ,因此对于无法容纳在内存中的大型文件,这将失败。 The rdbuf solution that NaCl gave will similarly have an issue with very large files. NaCl给出的rdbuf解决方案同样会遇到非常大的文件问题。

You can solve the large file problem by not reading all of the input at once. 您可以通过不立即读取所有输入来解决大文件问题。 However, this will most likely require you to restructure your code inside your parsers. 但是,这很可能需要您在解析器中重构代码。 Without more detail on their implementations, I can't point you in the right direction. 如果没有更详细的实现,我不能指出你正确的方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM