gpt4 book ai didi

c++ - std::streambuf::in_aval 总是为 std::ostream 返回 0

转载 作者:太空宇宙 更新时间:2023-11-04 13:24:04 26 4
gpt4 key购买 nike

我的目标是获取存储在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;

关于c++ - std::streambuf::in_aval 总是为 std::ostream 返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33936113/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com