3

我在措辞这个问题时遇到了麻烦(正如您从标题中看到的那样),但我会尝试:

如果布尔变量为真,我将打开一个文件流(ofstream),然后如果相同的布尔变量为真,则尝试再次关闭文件流会给出错误

'fout' was not declared in this scope"

这是一个最小的例子:

using namespace std;
#include <fstream>

int main(int argc, char * argv[]) {
    bool output = true;

    if (output) {
        ofstream fout("test.txt");
    }
    if (output) {
        fout.close();
    }
} // end main

我要做的是打开一个文件来存储程序的一些结果,只有当布尔“输出”为真时。我可以让它每次都打开文件(不测试),但一段时间后会变得非常混乱,因为真正的文件名取决于程序中设置的变量,我不想覆盖任何旧文件,所以我宁愿这样做。

编辑:今天我了解了“范围”是什么......谢谢大家!
工作代码如下:

using namespace std;
#include <fstream>

int main(int argc, char * argv[]) {
    bool output = true;
    ofstream fout;
    if (output) {
        fout.open("test.txt");
    }
    if (output) {
        fout.close();
    }
} // end main
4

3 回答 3

4

fout在 if 块的范围内声明,else 块具有单独的范围,它自己的自动变量fout不是一个。

然而你实际上不需要在这里担心它,ofstream当它超出范围时会自动关闭,因为它遵守 RAII。

http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization

我实际上让它关闭它的自我比做你自己更可取。

http://en.cppreference.com/w/cpp/io/basic_ofstream

(注意析构函数旁边的注释)。

int main(int argc, char * argv[]) {
    bool output = true;

    if (output) {
        ofstream fout("test.txt");
                    //do with fout, let it close itself
    }
} // end main

上面的代码很好。

于 2012-11-28T10:37:23.987 回答
1

该错误是因为您在“if 语句”中定义了“fout”,并且它没有在该区域之外(在 if 语句之外)定义,您可以这样做:

#include <fstream>
using namespace std ;

int main()
{
     ofstream fout ;
     bool output = true ;
     if(output)
     {
          fout.open("test.txt");
     }
     if(output)
     {
          fout.close(); 
     }
  }
于 2012-11-28T10:42:01.857 回答
0

深思熟虑:)

最小示例的简单解决方案是ofstream在需要使用它的时间内在它存在的范围内声明。然后,您只需在要实际使用流的地方设置条件语句:

{
    bool output = someArgOrTestResult;
    ofstream myOutStream;

    if( output ) mOutStream << "Whatever";

}

但是,如果您决定在某个时候改变行为,重复的条件语句可能会变得 (a) 丑陋,并且 (b) 难以维护。所以看看你在做什么并创建一个MyOutput类可能是有益的。

class MyOutput
{
private:
    std::string filename;
    bool output;
    ofstream fout;

public:
    MyOutput( const std::string& fn , bool out ) : filename(fn) , output(out) 
    {
         if( output )
             fout.open(filename); //Check syntax might need .c_str()       
    }

    ~MyOutput()
    {
         if( output )
             fout.close();
    }

    //There are many ways to expose the output function but simplest
    void write( const std::string& data )
    {
         if( output )
         {
             output << data;
         }
    }

};

注意- 在您需要输入的错误检查方面有很多缺失 - 例如,如果文件名无法打开会发生什么。

然后主要你可以有这样的东西:

#include <fstream>

int main(int argc, char * argv[]) {
    bool output = true;
    MyOutput fout("test.txt",output);

    std::string myLocalData = "Some stuff....";
    fout.write(myLocalData);


} // end main

现在的优点是您可以只使用语句来写入数据而无需周围的测试。output对此有一百万种变化,如果未设置,甚至可能访问您要编写的内容,但如果是这种情况,则可能也需要进行处理,MyOutput尽管它需要重命名和不同的方法...

于 2012-11-28T11:09:13.163 回答