C++ Read a whole File using ifstream
2015-08-17 20:16
495 查看
std::ifstream ifs("filename.txt");
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
Mind the extra parenthesis in the str declaration, it's necessary for correct parsing.
it's a string constructor that takes an input iterator pair. The first input iterator is an istreambuf_iterator initialized with the stream. The second input iterator is an istreambuf_iterator is default constructed. A default constructed istreambuf_iterator
returns equal to another istreambuf_iterator that has exhausted the input from the streambuf it was reading from. So the constructor reads from the first istreambuf_iterator until it runs out of data.
The first argument needs to go in parenthesis otherwise the compiler will parse the string declaration as a function declaration. Specifically a function that returns a string, called str that takes as a first argument a istreambuf_iterator<char> called ifs
and as a second argument an istreambuf_iterator<char> that is unnamed. Technically you can also wrap the second argument in parenthesis instead, but usually when you do it, you wrap the first one.
std::ifstream ifs("filename.txt");
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
Mind the extra parenthesis in the str declaration, it's necessary for correct parsing.
it's a string constructor that takes an input iterator pair. The first input iterator is an istreambuf_iterator initialized with the stream. The second input iterator is an istreambuf_iterator is default constructed. A default constructed istreambuf_iterator
returns equal to another istreambuf_iterator that has exhausted the input from the streambuf it was reading from. So the constructor reads from the first istreambuf_iterator until it runs out of data.
The first argument needs to go in parenthesis otherwise the compiler will parse the string declaration as a function declaration. Specifically a function that returns a string, called str that takes as a first argument a istreambuf_iterator<char> called ifs
and as a second argument an istreambuf_iterator<char> that is unnamed. Technically you can also wrap the second argument in parenthesis instead, but usually when you do it, you wrap the first one.
相关文章推荐
- 黑马程序员-[OC语言] 第二篇:继承、多态概述
- 线性表(顺序存储)C语言实现
- c/c++编译时,指定程序运行时查找的动态链接库路径
- 黑马程序员-[OC语言] 第一篇:类、对象的基本概述
- C++11新特性之自动类型判断以及匿名函数
- C++11新特性之std::bind与std::function
- C语言宏定义小结
- c++ assert
- Effective C++ 条款1 视C++为一个语言联邦
- 关于OJ G++ 、C++提交
- C语言实现 前序、中序、后序遍历二叉树
- 队列(C语言版)
- 黑马程序员-[C语言] 第四篇:文件操作总结
- c++ 内存管理
- 马踏棋盘C语言实现
- C++BuilderX8e Mysql存过程储过程的增、删、改
- c++中的点号(.),冒号(:)和双冒号(::)运算符
- 黑马程序员-----c语言基础与重点第二篇——进制转换与数组
- c++中如何将uint8_t按数字输出
- 黑马程序员-[C语言] 第二篇:数组、排序方法总结