在'if'条件中定义fstream

use*_*771 10 c++ fstream if-statement ifstream ofstream

答案中有以下代码:

if (std::ifstream input("input_file.txt"))
  ;
Run Code Online (Sandbox Code Playgroud)

这似乎很方便,将'input'变量的范围限制在确认有效的位置,但VS2015和g ++似乎都没有编译它.它是某些编译器特定的东西还是需要一些额外的标志?

在VS2015中,IDE突出显示"std :: ifstream"和"input_file.txt"以及最后一个括号."std :: ifstream"标记为"错误:此处不允许使用函数类型".

VS2015 C++编译器给出以下错误:

  • C4430缺少类型说明符 - 假设为int.注意:C++不支持default-int
  • C2059语法错误:'('

Nat*_*ica 14

你拥有的代码还不合法.在C++ 11之前,if语句可以是

if(condition)
if(type name = initializer)
Run Code Online (Sandbox Code Playgroud)

name将作为被评估bool,以确定条件.在C++ 11/14中,规则允许使用

if(condition)
if(type name = initializer)
if(type name{initializer})
Run Code Online (Sandbox Code Playgroud)

再次,在初始化以确定条件之后name评估为a bool.

从C++ 17开始,虽然您可以将if语句中的变量声明为复合语句,如for循环,它允许您使用括号初始化变量.

if (std::ifstream input("input_file.txt"); input.is_open())
{
    // do stuff with input
}
else
{
    // do other stuff with input
}
Run Code Online (Sandbox Code Playgroud)

应该注意的是,这只是语法糖,上面的代码实际上被翻译成了

{
    std::ifstream input("input_file.txt")
    if (input.is_open())
    {
        // do stuff with input
    }
    else
    {
        // do other stuff with input
    }
}
Run Code Online (Sandbox Code Playgroud)


Mar*_*k B 8

根据http://en.cppreference.com/w/cpp/language/if,该代码不合法​​(该网站非常有信誉但我可以根据需要寻找标准参考).您可以在if条件中声明变量,但必须用=或初始化它们{}.所以假设你至少拥有C++ 11,你可以这样做:

if (std::ifstream input{"input_file.txt"})
    ;
Run Code Online (Sandbox Code Playgroud)

  • OP的代码在C++ 17中仍然不合法.新的*init-statement*功能不会更改*condition*的必需形式. (2认同)