对cout或文本文件使用C++流



我有一个非常简单的程序,我会询问用户是想打印到屏幕还是文件。与其创建两组输出部分,我想我可以将流切换到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;
}

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

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

相关内容

  • 没有找到相关文章

最新更新