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

标签 c++ string file-io constructor

我正在使用 OpenGL,我需要将 VertexShader.glsl 的内容放入 std::string

我看过相关的 StackOverflow 帖子,但我真的不知道如何将数据类型和内容匹配在一起以使其工作。

Read file-contents into a string in 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";

最佳答案

constructor #6 here :

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

哪些是:

Constructs the string with the contents of the range [first, last).

istreambuf_iterator是:

a single-pass input iterator that reads successive characters from the std::basic_streambuf (ifs in this example) object for which it was constructed... The default-constructed std::istreambuf_iterator is known as the end-of-stream iterator. When a valid std::istreambuf_iterator reaches the end of the underlying stream, it becomes equal to the end-of-stream iterator.

content 由一对迭代器构成 - 第一个是我们对文件的单遍迭代器,第二个是流结束迭代器,充当哨兵。在本例中,string 构造函数引用的范围 [first, last) 是文件的全部内容。

关于c++ - 获取文件内容并将其放入 C++ 中的字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29737796/

相关文章:

java - 使用字符串数组来标记每个条目的字母

php - 比较 2 个字符串,减去相同的字符并返回新值

vb.net - 读取50M行的CSV文件,如何提高性能

python - 处理 JSON 中的错误转义字符

python - 在Python中查找扩展名为.txt的目录中的所有文件

c++ - 混合模板函数重载和继承

c++ - 分组数据的最佳关联容器是什么

PHP:从字符串末尾获取第n个字符

c++ - 如何缩短命令行命令?

c++ - 控制台 cout 动画 - C++