获取文件内容并将其放入C++中的字符串中

Bra*_*ean 8 c++ string file-io constructor

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

我不知道之后发生了什么

std :: string内容

每次我使用std :: string之前都是这样的

std::string name = "2bdkid";
Run Code Online (Sandbox Code Playgroud)

Bar*_*rry 9

这是构造函数#6:

template< class InputIt >
basic_string( InputIt first, InputIt last,
              const Allocator& alloc = Allocator() );
Run Code Online (Sandbox Code Playgroud)

这样做:

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

istreambuf_iterator 是:

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

content是从迭代器对构造的 - 第一个是我们的单遍迭代器到文件中,第二个是作为哨兵的流末端迭代器.该范围内[first, last)string构造函数是指,在这种情况下,该文件的全部内容.