AlwaysLearningNewStuff
AlwaysLearningNewStuff

Reputation: 3031

Different output format for cin/ofstream

INTRODUCTION AND RELEVANT INFORMATION:

Suppose I have the following class:

class Example
{
    int m_a;
    int m_b;
    public:
    // usual stuff, omitted for brevity
    friend ostream & operator<< (ostream & os, const Example &e)
    {
        return os << m_a << m_b;
    }
};

QUESTION:

I want to keep default behavior for cin, but the following format when writing to ofstream:

m_a , m_b

MY EFFORTS TO SOLVE THIS:

I have tried searching here, but haven't found any similar question.

I have tried searching online, but still haven't found anything helpful.

I have tried to add

friend ofstream & operator<< (ofstream & ofs, const Example &e)
{ 
    return ofs << m_a << ',' << m_b;
} 

into the class, but that produced a compiler error. To be honest, this approach feels wrong, but i had to try it before coming here for help.

Upvotes: 0

Views: 127

Answers (3)

Franck
Franck

Reputation: 1635

I initially thought you just have forgotten the object e in your implementation.

friend ostream & operator<< (ofstream & ofs, const Example &e)
{ 
   return ((ostream&) ofs) << e.m_a << ',' << e.m_b;
}

with the following explanation friend binary operator with 2 arguments inside a class are intrinsically external methods declared in the class body.

But after compiling with clang++, ofstream << int complains with the error: invalid operands to binary expression ('ofstream' (aka 'basic_ofstream') and 'int') and you should also add the cast to ostream.

In fact ofstream << int don't know if it should use ofstream << Equation or ostream << int and the ambiguity causes a compilation error.

So you should be aware of the overloading that is likely to generate future compilation errors.

Upvotes: 0

Khalil Khalaf
Khalil Khalaf

Reputation: 9407

A string's syntax is "S" even if it is one character string. And fstream takes a string and not a char. Therefore, this should work:

friend ofstream & operator<< (ofstream & ofs, const Example &e) 
{ 
    ofs << e.m_a << "," << e.m_b; // " instead of '
    return ofs;
} 

Upvotes: 0

Bo Persson
Bo Persson

Reputation: 92271

When chaining operators, all the standard << will return an ostream& reference.

Then your return ... will not work, because the value doesn't match the ofstream& return type.

Just use ostream& in your user defined operator<<, and it should work.

Upvotes: 2

Related Questions