我的目标是获取存储在streambuf
中的数据。我的想法是通过rdbuf
获取streambuf
,然后使用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。
为了访问存储在 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;
这将给出:
size: 10
content: 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;
我是一名优秀的程序员,十分优秀!