startresse
startresse

Reputation: 151

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

Upvotes: 0

Views: 65

Answers (1)

startresse
startresse

Reputation: 151

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

Upvotes: 1

Related Questions