[英]What's the difference between !ofstream.fail() and bool(ofstream)?
我目前正在學習如何寫入文件。 這是代碼:
#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
實例用作 boolean。它也能正常工作!
if (out) {
// write to the file...
}
那么使用if (.out.fail())
和if (out)
有什么區別呢?
誰能幫我?
.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())
相同。
如我錯了請糾正我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.