nook
nook

Reputation: 2396

c++ not writing to console unless a newline was encountered

I was recently writing a simple c++ program involving sockets. It had been a while since I worked with c++, so i was doing some simple sanity checking to make sure my classes were properly constructed. I encountered a very strange error then. When I did not have \n or endl at the end of my output to console, it would not write to console. For example:

This would not output to console

class Server{
    public:
        Server(){
            std::cout << "STARTING SERVER";
        }
};

This would:

class Server{
    public:
        Server(){
            std::cout << "STARTING SERVER" << std::endl;
        }
};

Both were created using Server server;. Was this just a 'ghost' in my computer or has anyone encountered this before?

Upvotes: 1

Views: 161

Answers (1)

David Schwartz
David Schwartz

Reputation: 182763

That's normal. It's stored in the buffer until the buffer is flushed. You can send std::flush to the stream to flush it. You can use std::endl to write an end of line and flush the buffer. It's basically an optimization to avoid large numbers of I/O operations if you write lots of small things to a stream.

Upvotes: 8

Related Questions