【问题标题】:Take file contents and put it into a string in C++获取文件内容并将其放入 C++ 中的字符串中
【发布时间】:2015-04-20 01:08:30
【问题描述】:

我正在使用 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:: 字符串内容

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

std::string name = "2bdkid";

【问题讨论】:

    标签: c++ string file-io constructor


    【解决方案1】:

    我是constructor #6 here:

    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) 是文件的全部内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 2018-07-14
      • 2020-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多