我正在尝试将整个流(多行)读入字符串中。
我正在使用这段代码,它有效,但它冒犯了我的风格感......当然有更简单的方法吗?也许使用字符串流?
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.
Actually, a
const
reference to a string would do as well, and that may make things easier...
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), {});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)