Search code examples
c++ofstreamostream

Remove code duplication with an ostream variable


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 << ?


Solution

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