给定一个简单的文件加载函数,
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()
。这意味着 c_str()
返回的值无效。
您需要确保返回的 std::string
对象至少在您持有通过调用 c_str()
返回的指针时仍然存在.例如:
std::string some_file = load_file("some_file");
std::string another_file = load_file("another_file");
printf("%s", some_file.c_str());
printf("%s", another_file.c_str());
关于c++ - 为什么 c_str() 会为两个不同的字符串返回相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23016688/