您的位置:首页 > 编程语言 > C语言/C++

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.          
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: