gpt4 book ai didi

c++ - 如何将整个流读入 std::string?

转载 作者:IT老高 更新时间:2023-10-28 12:12:12 24 4
gpt4 key购买 nike

我正在尝试将整个流(多行)读入字符串。

我正在使用这段代码,它可以工作,但它冒犯了我的风格......肯定有更简单的方法吗?也许使用字符串流?

void Obj::loadFromStream(std::istream & stream)
{
std::string s;

std::streampos p = stream.tellg(); // remember where we are

stream.seekg(0, std::ios_base::end); // go to the end
std::streamoff sz = stream.tellg() - p; // work out the size
stream.seekg(p); // restore the position

s.resize(sz); // resize the string
stream.read(&s[0], sz); // and finally, read in the data.


实际上,对字符串的 const 引用也可以,这可能会使事情变得更容易...

const std::string &s(... a miracle occurs here...)

最佳答案

怎么样

std::istreambuf_iterator<char> eos;
std::string s(std::istreambuf_iterator<char>(stream), eos);

(如果不是 MVP,可能是单线)

2011 年后的编辑,现在拼写这种方法

std::string s(std::istreambuf_iterator<char>(stream), {});

关于c++ - 如何将整个流读入 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3203452/

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