Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ avoiding newline with cout <<

Tags:

c++

io

ostream

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

like image 713
ZelelB Avatar asked Aug 04 '26 07:08

ZelelB


2 Answers

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;
}
like image 156
Sergey Kalinichenko Avatar answered Aug 06 '26 20:08

Sergey Kalinichenko


Answer

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:

  • to flush: use std::flush
  • to newline: use '\n' or append it to your string: "foobar!\n"
  • both: use std::endl

Advice

In 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.

like image 20
Sebastian Mach Avatar answered Aug 06 '26 22:08

Sebastian Mach