我目前正在学习如何写入文件。下面是代码:
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream out;
out.open("nbb.txt");
if (!out.fail()) {
// write something
} else {
cout << "Failed to open file!" << endl;
}
}因此,当我调用open()方法时,(如果文件不能打开),则条件out.fail()为真。但是,我尝试将out实例作为布尔值使用。它也能用!
if (out) {
// write to the file...
}那么使用if (!out.fail())和if (out)有什么区别呢?
有谁可以帮我?
发布于 2022-02-20 04:27:50
.fail()如果有任何问题,返回true,所以使用。
if(!out.fail())与if(not(false))相同,即if(true)。
当您说if(out)时,自动检查值是否为0以外的值,NULL和nullptr。
if(out)当存在值时,这将成为if(true)。
这使得if(out) and if(!out.fail())也是一样的。
如果我错了就纠正我
https://stackoverflow.com/questions/71190873
复制相似问题