【问题标题】:Is it possible to pass the stringbuf's streambuf direct to the filebuf?是否可以将 stringbuf 的 streambuf 直接传递给 filebuf?
【发布时间】:2017-01-08 21:15:47
【问题描述】:

我正在研究操纵 stringbuf 的函数,我需要将其保存在文件中。 如果我可以将 stringbuf 直接传递给 ofstream 的 filebuf,那将是一个巨大的优势。

我知道两者都使用 streambuf 对象,而不是我能以某种方式将 filebuf 的 streambuf 替换为我的 stringbuf 的流吗?

查看下面的代码以更好地理解这个想法:

#include <fstream>
#include <sstream>

void printit(std::stringbuf &MyBb) {
    std::ofstream fFile("newfile.txt");

    fFile.rdbuf(MyBb.rdbuf()); //MyBb doesn't have this member function
                               //How can I give to fFile the streambuf
                               //from my stringbuf?  
}

int main() {
    std::stringbuf MyB;

    MyB.sputn("First sentence\n",15);

    printit(MyB);

    return 0;
}

【问题讨论】:

    标签: c++ c++11 c++14 ofstream filebuf


    【解决方案1】:

    您只需要像向其写入字符串并使用您的函数一样。使用fFile &lt;&lt; MyPb.rdBuff(); 这应该可以工作

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 2018-04-17
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多