Considering the following code (it uses OpenGL but that's not what my question is about):
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
using std::string;
...
//Example func for loading content of external file
string load(string src) {
std::ifstream file(src);
if (file.fail()) {
output("FILE", "Failed to access content of file at location " + string(src), 1);
}
string content;
while (!file.eof()) {
char character;
file.get(character);
content.push_back(character);
}
content.pop_back();
return content;
};
unsigned int compileShader() {
// Create shader
unsigned int shader;
shader = glCreateShader(type);
string codeString = load(src); // Load shader from file here
const char* code = codeString.c_str(); // Convert to C string (needed in further computations)
// What does the code look like?
std::cout << code << std::endl;
// --> Finish to compute shader based on gathered code, etc.
glShaderSource(shader, 1, &code, NULL);
}
...
The compileShader() function, thus, loads the content of an external file written in GLSL, then converts the result to a C string as needed in order to be passed as an argument to the GL function glShaderSource(). And it works just fine.
Focusing only on this snippet, however:
string codeString = load(src); // Load shader from file here
const char* code = codeString.c_str(); // Convert to C string
// What does the code look like?
std::cout << code << std::endl;
This works properly. The std::cout statement prints the content of the shader at execution; the compilations succeeds. Yet I realized by accident (by trying to take shortcuts, that is) that the following doesn't work:
const char* code = load(src).c_str(); // Load shader from file and convert to C string
// What does the code look like?
std::cout << code << std::endl;
The std::cout just prints a line instead of the file's content. Why is it so? I suppose it's a question of precedence (of the method over the function, perhaps?), but I've tried setting the function in brackets (as if it were a mathematical operation), to no avail.
What's preventing it from working? What are the underlying mechanics behind this? Thank you for your answers. I'm relatively new to C++, so it might really be simple, only I don't know where else exactly to search for an answer.