0

When I want to save result to file I use ofstream, right?

ofstream myout; 
myout.open (sav_fl, fstream::app);

But depending on the "ol" value(=user input),
I want to show it to screen not to file. How can I do?
I thought this way. But error message shown up.

if (ol == 1) myout = std::cout; // My code

"error: no match for ‘operator=’ in ‘myout = std::cout’
/usr/include/c++/4.4/iosfwd:84: note: candidates are: std::basic_ofstream<char, std::char_traits<char> >& std::basic_ofstream<char, std::char_traits<char> >::operator=(const std::basic_ofstream<char, std::char_traits<char> >&)"

And how can I use it in sentence?
I thought this way.

myout << "this is test" << endl;   //My code, is it right?

Thanks you guys..

Edited by Nick Evan: Added code-tags

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by firstPerson
1

You need to make it a reference.
In fact do something like this :

void write(const string& str, std::ostream& out = cout){
 out << str << endl;
}

Now you can call the code like this :

write("Hello"); // and prints to screen
write("Hello",myout); //and write to file
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.