[英]std::ifstream initial value checks as true when uninitialized
我意識到,當我測試std :: ifstream的值而不初始化它時,它會檢查為true。
如何初始化流,直到打開要使用的文件,檢查才會返回false?
(或者也許我不應該使用流的值來確定它是否已打開?)
顯示問題的小例子:
std::ifstream stream;
bool iWantToUseTheStream = false;
if (iWantToUseTheStream)
stream.open(someFileName, std::fstream::in);
if (stream) // checks as true whether I opened the stream or not !
std::cout << "I don't want this to print if I did not open the stream !";
可以使用is_open()
成員函數檢查文件是否打開,而不是檢查整個流的狀態。 那會讓你的代碼看起來像
std::ifstream stream;
bool iWantToUseTheStream = false;
if (iWantToUseTheStream)
stream.open(someFileName, std::fstream::in);
if (stream.is_open()) // is only true if there is an open file
std::cout << "I will only print if the file is open";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.