I have a function that reads a file and returns a string.
string get_file_contents(const char *filename)
{
ifstream in(filename);
if (in)
{
ostringstream contents;
contents << in.rdbuf();
in.close();
return(contents.str());
}
throw(errno);
}
I read a file containing only success
and convert the return value it into a c
style string in two different ways with different results.
string str = get_file_contents("test.txt");
const char* str1 = str.c_str();
cout << "printing str1: ";
cout << str1 << endl;
const char* str2 = get_file_contents("test.txt").c_str();
cout << "printing str2: ";
cout << str2 << endl;
output:
printing str1: success
printing str2:
I don't understand why str2 is empty. Any insight is appreciated.