c++ - 为什么 c_str() 会为两个不同的字符串返回相同的值?

标签 c++ string

给定一个简单的文件加载函数,

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/

相关文章:

c# - 在字边界上将字符串拆分为 2 个字符串以最小化长度差异的优雅方法

c++ - 遍历 cv::Mat 中包含的 cv::Points

c++ - 使用 cilk 计算 Fibonacci 的正确方法是什么?

c++ - Operator= 在 C++ 中重载

string - NSFontAttributeName 已更改为 String

python - 在python中读取文件后返回单词列表

c++ - 在不知道矩阵名称的情况下读取 OpenCV 中的 YML

c++ - C 或 C++ 中的标准输入 : Spotify: Reverse Binary Puzzle

Python 3.6+ 格式化解包字典中缺少键的字符串

string - 将数字转换为 YYYYMM