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?
That’s normal. It’s stored in the buffer until the buffer is flushed. You can send
std::flushto the stream to flush it. You can usestd::endlto 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.