如何读取整个流到std :: string? [英] How to read entire stream into a std::string?

查看:275
本文介绍了如何读取整个流到std :: string?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取一个整个流(多行)到一个字符串。



我使用这个代码,它的工作原理,但它冒犯我的风格感...当然有一个更容易的方法?也许使用stringstreams?

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

int p = stream.tellg(); //记住我们在哪里

stream.seekg(0,std :: ios_base :: end); // go to the end
int 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); //最后,读入数据。



编辑



实际上,一个 const引用到字符串也可以,这可以使事情更容易...

  const std :: string& s(...这里出现一个奇迹...)


解决方案

如何

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

(如果不是MVP,可以是单行)



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

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


I'm trying to read an entire stream (multiple lines) into a string.

I'm using this code, and it works, but it's offending my sense of style... Surely there's an easier way? Maybe using stringstreams?

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

  int p = stream.tellg();  // remember where we are

  stream.seekg(0, std::ios_base::end); // go to the end
  int 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.

EDIT:

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...)

解决方案

How about

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

(could be a one-liner if not for MVP)

post-2011 edit, this approach is now spelled

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

这篇关于如何读取整个流到std :: string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆