相关疑难解决方法(0)

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

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

我正在使用这个代码,它有效,但它冒犯了我的风格......当然有一种更简单的方法吗?也许使用stringstreams?

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.
Run Code Online (Sandbox Code Playgroud)


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

const std::string &s(... a miracle occurs here...)
Run Code Online (Sandbox Code Playgroud)

c++ string stream

68
推荐指数
4
解决办法
5万
查看次数

标签 统计

c++ ×1

stream ×1

string ×1