How to read entire stream into a std::string?(如何将整个流读入 std::string?)
问题描述
我正在尝试将整个流(多行)读入一个字符串.
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;
  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 引用也可以,这可能会使事情变得更容易...
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 可能是单线)
(could be a one-liner if not for MVP)
2011 年之后的编辑,这种方法现在拼写
post-2011 edit, this approach is now spelled
std::string s(std::istreambuf_iterator<char>(stream), {});
                        这篇关于如何将整个流读入 std::string?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将整个流读入 std::string?
				
        
 
            
        基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 这个宏可以转换成函数吗? 2022-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				