I've had to stop coding so many projects because of this weird quirk that I'm fed up enough to ask and risk looking like an idiot, so here goes...
I wrote a function like this:
const char* readFileToString(const char* filename) {
const char* result;
std::ifstream t(filename);
std::stringstream buffer;
buffer << t.rdbuf();
result = buffer.str().c_str();
return result;
}
I would expect that, if file.txt
contains hello
, that readFileToString("file.txt")
should return hello
. Instead, it returns garbled text, something along the lines of H�rv�0
. However, if I put a std::cout << result;
just before the return, it'll print hello
.
Is this some weird, impossible quirk with C++? How do I fix it?