-1

I am writing a method which requires reading a file and putting all its contents into a string variable.

This is what I have tried:

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;

}

And this is the error I get:

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;
        ~~~~~~~~~~ ^  ~~~~

Instead of sourceCode << line, which is obviously wrong, what shall be used?

M.E.
  • 3,994
  • 3
  • 20
  • 76

2 Answers2

1

Don't use << to append something in a string.

Rather than:

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

Consider:

while (getline(shaderFile, line)) {
    sourceCode += line;
}
Rohan Bari
  • 6,523
  • 3
  • 9
  • 30
0

You cannot stream into a string using <<. You could use an istringstream, or += with the string (but this will re-create the string for every line).

So I would just use this to read the whole file directly into the string:

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;
}
Mika Fischer
  • 3,266
  • 1
  • 21
  • 26