abalter
abalter

Reputation: 10383

Using C++ stream for cout or text file

I have a very simple program where I ask the user if they want to print to screen or a file. Rather than create two sets of output sections, I thought I could switch a stream to either cout or an ofstream and then output to that stream. However, I'm getting screen output no matter what.

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

Upvotes: 0

Views: 2235

Answers (1)

juanchopanza
juanchopanza

Reputation: 227418

You could put all the writing logic inside a function, and let the caller decide which output stream to write to:

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

then

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

Upvotes: 3

Related Questions