0

I have

void fnc(std::ofstream& file){
    std::cout << x;
    file << x;
}

with x something complicated and I would like to remove the code duplication.

I tried something like

void fnc(std::ofstream& file){
    std::ostream os;
    os << x;
    std::cout << os;
    file << os;
}

but it doesn't work. What's the best way to remove code duplication with the operator << ?

startresse
  • 151
  • 10
  • I don't understand – Big Temp May 15 '20 at 21:05
  • 1
    I think you wanted std::ostringstream instead of std::ostream: [https://stackoverflow.com/questions/12233710/how-do-i-use-the-ostringstream-properly-in-c](https://stackoverflow.com/questions/12233710/how-do-i-use-the-ostringstream-properly-in-c) – drescherjm May 15 '20 at 21:07
  • 1
    Or you can call fnc(std::cout) and get the cout out of the first code. – drescherjm May 15 '20 at 21:09
  • I want the thing both outputed and printed in an external file, but I didn't want to copy paste for future modification (ouput and file must be the same) – startresse May 15 '20 at 21:14

1 Answers1

1

Thanks to drescherjm the solution is the following :

void fnc(std::ofstream& file){
    std::ostringstream os;
    os << x;
    std::cout << os.str();
    file << os.str();
}
startresse
  • 151
  • 10