为什么在某些情况下不写入此文件?

Why isn't this file being written to under certain conditions?

本文关键字:文件 情况下 为什么      更新时间:2023-10-16

所以我在这个网站上查看了不同的问题和答案,其中一个提到了一种测试程序是否运行过多次的方法。我决定尝试一下,但遇到了一个错误。

这应该是一个简单的测试程序,根据(最初为空的(文本文件check.txt是否以x开头来做两件不同的事情:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
fstream file("check.txt", ios::in | ios::out);
if(!file){
cerr << "no file" << endl;
return 1;
}
char ch;
file >> ch;
if(ch == 'x'){
cout << "result one" << endl;
}
else {
cout << "result two" << endl;
file << 'x';
}
return 0;
}

我不太确定这里出了什么问题。

代码中有两个主要问题:

file.fail()

这是你应该检查的情况,不要!文件其次,使用<lt;操作员请阅读<lt;操作员:http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/.

相关文章: