7

我有,可能是微不足道的问题,但我无法理解。我写了简单的代码:

fstream file;
file.open("data", ios::in);
if(!file.good()){
   file.close();
   file.open("data", ios::out);
   if(!file.good()) cout<<"not good"<<endl;
   file<<"test"<<endl;
   file.close();
}

在新鲜的 VS8 C++ Express 项目中。当我运行它并且“数据”不存在时,它会创建文件,但也会返回“不好”(第二个),因此输出不会写入文件中。现在有趣的事情来了。如果我在 VS10 C++ Express 和 Code::Blocks 12 中编译相同的代码,它工作正常。

为什么会这样?

@edit 我的朋友也在他的 PC 上使用 VS8 C++ Expres 进行了检查。对他也一样。

@edit2 与我对“解决方案”的评论相同:

使用 .clear() 强制清除故障位;方法似乎有效。当您在较新的 IDE 中学习然后必须切换到较旧的 IDE 时会很痛苦:/。寿,它给了很好的教训。多谢你们。

4

1 回答 1

4

This was by design. In C++98, closing an fstream does not clear the error state and calling open() on an fstream does not reset the error state. See LWG Defect #409 for a discussion of the issue.

The behavior was changed in C++11 such that the error state is cleared (via a call to clear()) if the open operation succeeds.

于 2013-06-11T20:46:15.327 回答