使用C ++流来获取cout或文本文件

时间:2014-10-13 19:36:05

标签: c++ stream cout ofstream ostream

我有一个非常简单的程序,我询问用户是否要打印到屏幕或文件。我认为可以将流切换到cout或ofstream然后输出到该流,而不是创建两组输出节。但是,无论如何,我都会获得屏幕输出。

ostream &out = cout;

do
{
    cout << "Write to file (f) or screen (s)?";
    cin >> yes_or_no;
} while (yes_or_no != 'f' && yes_or_no !='s');

if (yes_or_no=='f')
{
    ofstream out;
    out.open("Report.txt");
    cout << "Writing report to Report.txt" << endl;
    system("pause");
}

out << "Day:        Current Value         ROI" << endl;
out << "------------------------------------------" << endl;
out << setw(5) << 0;
out << "$" << setw(20) << setprecision (2) << fixed << initial_value;
out << setw(12) << "1.00" << endl;
for (int day = 1 ; day < number_of_days ; day++)
{
    current_value = generateNextStockValue(current_value, volatility, trend);
    out << setw(5) << day;
    out << setw(20) << setprecision (2) << fixed << current_value;
    out << setw(12) << setprecision (2) << fixed << current_value / initial_value;
    out << endl;
}

1 个答案:

答案 0 :(得分:2)

您可以将所有写入逻辑放在一个函数中,让调用者决定写入哪个输出流:

void do_the_stuff(std::ostream& os)
{
  // write to os
  os << "blah blah" ....
}

然后

if (yes_or_no=='f')
{
  ofstream out("Report.txt");
  do_the_stuff(out);
} else {
  do_the_stuff(std::cout);
}