Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ overloaded << operator does not correctly output unless I include an endl

pretty interesting issue I'm having.

Basically I'm overloading the insertion operator to return a string representation of my class. However, the program just terminates unless I include a std::endl.

template<class T>
std::ostream& operator << (std::ostream& outs, const LinkedQueue<T>& q) {

    outs << "queue[";

    if (!q.empty()) {
        outs << q.front->value;

        for (auto i = ++q.begin(); i != q.end(); ++i)
            outs << ',' << *i;
    }
    outs << "]:rear";

    return outs;
}

int main() {
    QueueType queueType1;
    queueType1.enqueue("L");
    std::cout << queueType1 << std::endl;
   return 0;
}

The above main produces the correct output of: queue[L]:rear

But, if I remove the std::endl from main, the program breaks and produces nothing.

I cannot include an endl in the overloaded method because it adds an extra character to my string that I do not what. Any suggestions?

like image 577
Yasin Z Avatar asked Dec 21 '25 17:12

Yasin Z


1 Answers

As @samevarshavchik suggests, use std::flush instead of std::endl to accomplish the desired output. This can be done in main:

int main() {
    QueueType queueType1;
    queueType1.enqueue("L");
    std::cout << queueType1 << std::flush;
                              /*^^^here^^^*/
    return 0;
}

Or inside your overload function:

template<class T>
std::ostream& operator << (std::ostream& outs, const LinkedQueue<T>& q) {

    outs << "queue[";

    if (!q.empty()) {
        outs << q.front->value;

        for (auto i = ++q.begin(); i != q.end(); ++i)
            outs << ',' << *i;
    }
    outs << "]:rear" << std::flush;
                      /*^^^here^^^*/
    return outs;
}
like image 64
NonCreature0714 Avatar answered Dec 23 '25 07:12

NonCreature0714



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!