Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 未初始化时,ifstream初始值检查为true_C++_Stream - Fatal编程技术网

C++ 未初始化时,ifstream初始值检查为true

C++ 未初始化时,ifstream初始值检查为true,c++,stream,C++,Stream,我意识到,当我在没有初始化的情况下测试std::ifstream的值时,它会检查为true 如何初始化流,使其在打开要使用的文件之前,检查返回false 或者我不应该使用流的值来确定它是否已打开 显示问题的小示例: std::ifstream stream; bool iWantToUseTheStream = false; if (iWantToUseTheStream) stream.open(someFileName, std::fstream::in); if (stream)

我意识到,当我在没有初始化的情况下测试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 !";

您可以使用member函数检查文件是否打开,而不是检查整个流的状态。这将使您的代码看起来像

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";

为什么不检查文件名呢?如果文件名有误,或者您没有读取文件的权限,只需知道文件名即可。@NathanOliver看起来我应该这么做!真不敢相信我要问这么简单的事情哈哈。谢谢:D@Norgannon要我写下来作为你的答案,还是你只想删除这个?@NathanOliver,随你的便