C++ 用简单的代码同时写入文件和控制台输出

2024-04-02

我试图将以下整个函数写入文本文件,同时仍然保持其控制台输出功能,而没有代码冗余。是否有一种简单的方法可以将整个方法的结果同时发布到文件和控制台?

#include<iostream>
#include<fstream>
  void sports(){
      cout<<"\nGame_Code\t\tGane\t\tCost\t\tStart Time\n";
      cout<<"\nSP-9651\t\t Game 1 \t\t60\t\t08:00";
      cout<<"\nSP-9652\t\t Game 2 \t\t60\t\t09:15";
      cout<<"\nSP-9653\t\t Game 3 \t\t55\t\t09:55";
      cout<<"\nSP-9654\t\t Game 4 \t\t55\t\t11:00";
      cout<<"\nSP-9655\t\t Game 5 \t\t50\t\t13:00";
      cout<<"\nSP-9657\t\t Game 7 \t\t45\t\t19:45";
      cout<<"\nSP-9659\t\t Game 8 \t\t70\t\t22:45";
      cout<<"\n\n";
     } 
    int main(){
    //This is for console output
    sports();
    }

流可以传递给函数。因此,有一个打印函数可以执行这两种输出。

void print(std::ostream &os1, std::ostream &os2, const std::string &str)
{
    os1 << str;
    o22 << str;
}

void sports()
{
    std::fstream file("filename");

    print(std::cout, file, "\nSP-9651\t\t Game 1 \t\t60\t\t08:00");
    print(std::cout, file, "\nSP-9652\t\t Game 2 \t\t60\t\t09:00");
    print(std::cout, file, "\nSP-9653\t\t Game 3 \t\t60\t\t10:00");
    //... etc
}

int main()
{
    sports();
    return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 用简单的代码同时写入文件和控制台输出 的相关文章

随机推荐