C ++使用简单的代码同时写入文件和控制台输出 [英] C++ Writing to file and Console Output at the same time with simple code

查看:162
本文介绍了C ++使用简单的代码同时写入文件和控制台输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write the following entire function to a text file while still maintaining its console output functionality without having code redundancy. Is there a simple way to post an entire method's result to a file and console at the same time?

#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();
    }

推荐答案

流可以传递给函数.因此,有一个同时输出两个输出的打印功能.

Streams can be passed to functions. So have a print function that does both outputs.

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

这篇关于C ++使用简单的代码同时写入文件和控制台输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆