将文件内容读入 C++ 字符串中

8
我正在使用OpenGL,我需要将VertexShader.glsl文件的内容放入std :: string中。
我查看了相关的StackOverflow帖子,但我不知道如何匹配数据类型等使其正常工作。
例如,参考此处在C++中读取文件内容到字符串
#include <fstream>
#include <string>

int main(int argc, char** argv)
{

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

  return 0;
}

我不知道在

std:: string content

之后发生了什么。

我以前使用std::string的时候,每次都是像这样的:

std::string name = "2bdkid";
1个回答

9

这是 这里的构造函数 #6

template< class InputIt >
basic_string( InputIt first, InputIt last,
              const Allocator& alloc = Allocator() );

这个函数的作用是:

使用范围[first, last)的内容构建字符串。

istreambuf_iterator是:

一个单向输入迭代器,从构造它的std::basic_streambuf对象(在此示例中为ifs)中读取连续的字符... 默认构造的std::istreambuf_iterator称为流结束迭代器。当有效的std::istreambuf_iterator到达底层流的末尾时,它将等于流结束迭代器。

content由迭代器对构造 - 第一个是文件的单向迭代器,第二个是充当标记的流结束迭代器。 在这种情况下,string构造函数所引用的范围[first, last)是文件的全部内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接