gpt4 book ai didi

c++ - std::ifstream 初始值在未初始化时检查为真

转载 作者:行者123 更新时间:2023-11-28 04:31:41 26 4
gpt4 key购买 nike

我意识到当我在没有初始化的情况下测试 std::ifstream 的值时,它检查为真。

如何初始化我的流,直到我打开我想使用的文件,检查才会返回 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";

关于c++ - std::ifstream 初始值在未初始化时检查为真,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52721666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com