I'm starting C / C ++, trying to create something that seems like a fairly simple program: it loads the file into a c-line (const char *). However, although the program is incredibly simple, it does not work as I understand it. Take a look:
#include <iostream> #include <fstream> std::string loadStringFromFile(const char* file) { std::ifstream shader_file(file, std::ifstream::in); std::string str((std::istreambuf_iterator<char>(shader_file)), std::istreambuf_iterator<char>()); return str; } const char* loadCStringFromFile(const char* file) { std::ifstream shader_file(file, std::ifstream::in); std::string str((std::istreambuf_iterator<char>(shader_file)), std::istreambuf_iterator<char>()); return str.c_str(); } int main() { std::string hello = loadStringFromFile("hello.txt"); std::cout << "hello: " << hello.c_str() << std::endl; const char* hello2 = loadCStringFromFile("hello.txt"); std::cout << "hello2: " << hello2 << std::endl; hello2 = hello.c_str(); std::cout << "hello2 = hello.c_str(), hello2: " << hello2 << std::endl; return 0; }
The result is as follows:
hello: Heeeeyyyyyy hello2: 青! hello2 = hello, hello2: Heeeeyyyyyy
The initial value of hello2 changes every time, always some kind of random kanji (I use a Japanese computer, so I suppose it's somehow kanji).
In my naive view, it seems that two values should print the same way. One function returns a C ++ string, which is then converted to a c-string, and the other loads the string, converts the c-string from it, and returns it. I made sure that the line loaded properly in loadCStringFromFile by subtracting the value before I returned it, and indeed it was what I thought, for example:
const char* result = str.c_str(); std::cout << result << std::endl;
So why should the value change? Thanks for the help...
source share