给出一个简单的文件加载功能,为什么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