【问题标题】:How do I read a file in C++ and write contents into a string? [duplicate]如何在 C++ 中读取文件并将内容写入字符串? [复制]
【发布时间】:2020-08-28 14:19:59
【问题描述】:

我正在编写一个需要读取文件并将其所有内容放入字符串变量的方法。

这是我尝试过的:

unsigned int ShaderHandler::CompileShader(unsigned int shaderType, const std::string& sourceFilename) {

    std::string sourceCode;    
    std::string line;
    std::ifstream shaderFile;

    shaderFile.open(sourceFilename);

    while (getline(shaderFile, line)) {
        sourceCode << line;
    }

    shaderFile.close(); 

    std::cout << sourceCode;

}

这是我得到的错误:

ShaderHandler.cpp:30:20: error: invalid operands to binary expression ('std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') and 'std::string')
        sourceCode << line;
        ~~~~~~~~~~ ^  ~~~~

sourceCode &lt;&lt; line,显然是错误的,应该用什么?

【问题讨论】:

  • sourceCode += line;?

标签: c++


【解决方案1】:

不要使用&lt;&lt; 在字符串中追加内容。

而不是:

while (getline(shaderFile, line)) {
    sourceCode << line;
}

考虑:

while (getline(shaderFile, line)) {
    sourceCode += line;
}

【讨论】:

    【解决方案2】:

    您不能使用&lt;&lt; 流式传输到字符串中。您可以将istringstream+= 与字符串一起使用(但这会为每一行重新创建字符串)。

    所以我会用它直接将整个文件读入字符串:

    std::string read_file(const std::string& filename) {
        std::string result;
        std::ifstream file(filename);
        std::copy(std::istream_iterator<char>(file), std::istream_iterator<char>(),
                  std::back_inserter(result));
        return result;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-02-24
      • 2010-09-15
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多