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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With