简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM