3

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?

amanuel2
  • 4,508
  • 4
  • 36
  • 67
Yasin Z
  • 31
  • 1
  • 5
    You are mistaken. There's nothing wrong with the shown code, however, if you wish, you can use `outs << std::flush;` to explicitly flush the stream buffer. – Sam Varshavchik Oct 26 '16 at 02:29
  • Duplicate to https://stackoverflow.com/questions/22026751/c-force-stdcout-flush-print-to-screen – Mine Oct 26 '16 at 02:48

1 Answers1

1

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;
}
NonCreature0714
  • 5,744
  • 10
  • 30
  • 52