-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?

1
  • 3
    sourceCode += line;? Commented May 12, 2020 at 16:28

2 Answers 2

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.