【问题标题】:how to call a cout function to ofstream output file如何调用 cout 函数来输出文件
【发布时间】:2013-04-28 05:02:23
【问题描述】:

我有一个函数 void displayList() 显示一组列表。 在main函数中我也有

ofstream outputFile(output.txt)

如何调用 displayList 并将其打印到 output.txt 中?谢谢。

displaylist 只是一些 cout 行

【问题讨论】:

    标签: c++ printing output fstream ofstream


    【解决方案1】:

    假设您的 DisplayList 当前类似于:

    void DisplayList() { 
       cout << "a" << a << "\n";
    }
    

    我会将它重写为两个重载函数:

    void DisplayList(std::ostream &os) { 
        os << "a" << a << "\n";
    }
    
    void DisplayList() { DisplayList(std::cout); }
    

    然后你现有的代码可以继续不带参数调用DisplayList() 并获取当前行为。想要指定目标文件的代码可以调用:

    Displaylist(outputFile);
    

    并且输出将到达他们指定的文件而不是cout

    这可以作为一个带有默认参数的函数来完成,但在这种情况下,我认为一对重载函数可能更简单。

    【讨论】:

    • 我试过这样做,但是当它说 ostream 没有被声明时是什么意思?谢谢。
    • @LeonardLie:您可能没有在该文件中包含正确的标题。
    【解决方案2】:

    我相信是:

    outputFile << displayList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 1970-01-01
      • 2011-05-08
      • 2014-05-07
      相关资源
      最近更新 更多