if(!file)
和 if(!file.is_open())
有什么区别?
我用它们来检查文件是否已成功打开/读取。
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ifstream file;
// first one
if (!file)
cout<<"File is not opened"<<endl;
else
. . .
//second one
if (!file.is_open())
cout<<"File is not opened"<<endl;
else
. . .
}
最佳答案
c++ 文档解释了 operator!
Returns
true
if an error has occurred on the associated stream. Specifically, returnstrue
ifbadbit
orfailbit
is set inrdstate()
另一方面,is_open()
Checks if the file stream has an associated file. Returns
true
if the file stream has an associated file,false
otherwise
如果您想知道文件是否成功打开,请使用is_open()
。它也更能表达您的意图。
关于c++ - (!file) 和 (!file.is_open()) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59919741/