How could I avoid the newline in this code..
void ListEl::display() {
BaseEl::display();
cout << " Asis: " << anemnesis << endl;
}
here is BaseEl::display()
void BaseEl::display() {
cout << "P: " << priority << "\tN: " << name << endl;
}
it prints always the output of BaseEl::display(); then a newline, and then the " Asis: " << anemnesis << endl;
I tried cout << BaseEl::display() << " Asis: " << anemnesis << endl; but it didnt work neither
You cannot fix this without modifying BaseEl::display() to stop producing new line at the end of the output.
In general, it is a bad idea to add endl to your own output. Let the caller do that if he needs a newline.
Note that a more C++-like approach to output of your own classes is providing an implementation of operator << for the output. If you want virtual dispatch with it, provide an implementation at the level of the base class, and add a virtual member function for derived classes to override:
class BaseEl {
protected:
virtual void writeToStream(ostream& ostr) const;
friend ostream& operator << (ostream& ostr, const BaseEl& val);
};
class ListEl : public BaseEl {
protected:
virtual void writeToStream(ostream& ostr) const;
};
ostream& operator << (ostream& ostr, const BaseEl& val) {
val.writeToStream(ostr);
return ostr;
}
The meaning of endl is to print a newline-character and flush the output buffer. Hence you need to remove it from where you do not want a newline character.
Flushing the output buffers excessively can lead to performance loss and is normally not needed to be done manually, so as a general rule, avoid endl (unless, as said, you explicitly want to newline and flush).
In short, as general rules:
std::flush'\n' or append it to your string: "foobar!\n"std::endlIn C++, object serialization is done through overloading operator<< and operator>>, such that you can write
ListEl mylist;
std::cout << "The list: " << mylist << '\n';
Canonically, for output, it looks like this:
class Foobar {
friend std::ostream& operator<< (std::ostream& os, Foobar const &);
};
// might go into implementation file
std::ostream& operator<< (std::ostream& os, Foobar const &foobar) {
// print work
....
// Do not forget to return the stream
return os;
}
Letting that operator be a friend is a consequence of operator<<(std::ostream &, Foobar const&) not being inline-able within Foobar. If the print-function does not need access to private members, skip the friend.
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