1

我的目标是获取存储在streambuf. 我的想法是streambuf通过rdbuf然后使用sgetn.

class mystreambuf : public std::streambuf {}

mystreambuf strbuf;
std::ostream os(&strbuf);
os << "1234567890";
std::streambuf *sb = os.rdbuf();
std::streamsize size = sb->in_avail();

我希望得到 10,但我从in_avail方法返回 0。

4

1 回答 1

0

为了访问存储在std::streambuf中的数据,您可以将std::ostream链接到std::stringbuf并使用以下方法获取其内容std::stringbuf::str()

std::stringbuf strbuf;
std::ostream os(&strbuf);  
os << "1234567890";

std::string content(strbuf.str());
std::cout << "size: " << content.size() << std::endl;
std::cout << "content: " << content << std::endl;

这将给出:

尺寸:10
内容:0123456789

更短的方法是使用std::stringstream

std::ostringstream os;  
os << "1234567890";

std::string content(os.str());
std::cout << "size: " << content.size() << std::endl;
std::cout << "content: " << content << std::endl;
于 2015-12-01T22:45:52.827 回答