当我运行以下代码时,当 getline
运行时,foobar_fname
会被 foobar_fname
的内容覆盖:
ostringstream st_foobar_fname;
st_foobar_fname << foostr << BAR_CONST << barstr;
const char *foobar_fname = (st_foobar_fname.str()).c_str();
ifstream foobar_file(foobar_fname);
debug("Reading '%s'", foobar_fname);
string foobar_def = "";
if (getline(foobar_file, foobar_def)) {
debug("'%s' reported message '%s'", foobar_fname, foobar_def.c_str());
} else {
error("Unable to read '%s'", foobar_fname);
}
例如,如果 foobar_fname=/home/user/fname
和 /home/user/fname
包含“simple-text-content”,则输出如下所示:
Reading '/home/user/fname'
'simple-text-content' reported message 'simple-text-content'
但是,如果 /home/user/fname
不存在(且 getline
失败),则输出正确:
Reading '/home/user/fname'
Unable to read '/home/user/fname'
我哪里出错了?
(这是一段旧代码,我不想为其引入新的依赖项,因此 c++11、boost 等不是可行的解决方案)。
最佳答案
您正在看到未定义行为的症状。
st_foobar_fname.str()
返回一个std::string
。
const char *foobar_fname = (st_foobar_fname.str()).c_str();
存储一个指针,该指针在该行完成执行后无效,因为它对应于一个临时对象。临时对象被销毁,您只剩下一个悬空指针。
如果您想保留该值,请使用 std::string
。
std::string foobar_fname = st_foobar_fname.str();
关于c++ - 为什么 std::getline 会覆盖包含文件名的 char 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38212643/