是否可以将字符串的 streambuf 直接传递给 filebuf?

Is it possible to pass the stringbuf's streambuf direct to the filebuf?

本文关键字:filebuf streambuf 字符串 是否      更新时间:2023-10-16

我正在研究操作字符串的函数,我需要将其保存在文件中。如果我能将 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 sentencen",15);
    printit(MyB);
    return 0;
}

你只需要像给它写一个字符串一样,然后使用你的函数。使用fFile << MyPb.rdBuff(); 这可能应该有效