c++ - 将 C++ 流用于 cout 或文本文件

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

最佳答案

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

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

关于c++ - 将 C++ 流用于 cout 或文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26347588/

相关文章:

C++,linux,如何将非静态方法从单例传递给 pthread_create?

c++ - 为什么当我只使用静态 .lib 时 Windows 告诉我找不到 .dll 文件?

php - 我可以使用不是磁盘上文件的证书来使用 SSL 套接字吗? (即在数据库中)

c++ - "cout"和 "char address"

c++ - 方法的声明更改了符号的含义

c++ - 特征张量模块 : how to swap cols or rows?

linux - RTMP_ReadPacket,读取RTMP包头失败 rtmp ://a. rtmp.youtube.com/live2: Unknown error occurred

c++ - 状态机回放的流数据

c++ - 为什么从我的函数中删除 'cout' 会改变它的结果?

c++ - 为什么不能将 cout 与用户定义的转换一起使用到 std::string?