給出一個簡單的文件加載功能,爲什麼c_str()爲兩個不同的字符串返回相同的值?
std::string load_file(const std::string &filename) {
std::ifstream file(filename);
std::string line;
std::stringstream stream;
while (std::getline(file, line)) {
stream << line << "\n";
}
return stream.str();
}
爲什麼以下打印的another_file
兩倍的內容是什麼?
const char *some_file = load_file("some_file").c_str();
const char *another_file = load_file("another_file").c_str();
printf("%s", some_file);
printf("%s", another_file);
我不認爲在返回值上調用c_str()而不顯式存儲字符串是安全的。比較some_file和another_file的指針值,我認爲它們是一樣的。 – Ryp
ifstream在C++ 11中也沒有使用std :: string。 https://stackoverflow.com/a/37542/2591612 – Brian