简体   繁体   中英

Using std::endl vs “\n” when cin and cout are untied

Fast I/O recommends the use of following two line during programming competitions to speed up IO:

    ios_base::sync_with_stdio(false); 
    cin.tie(NULL);  

I can understand removal of sync. But after untying cin and cout how do I ensure that the buffer doesn't get overflowed, cin and cout work properly without blocking and buffer gets flushed properly when I am not using std::endl. Does the use of "\\n" automatically handles it?

how do I ensure that the buffer doesn't get overflowed,

The output buffer doesn't "overflow". When it gets full, it is automatically flushed, ie its contents are written out and its length is reset to 0. This is the case whether cin / cout are tied or not.

cin and cout work properly without blocking

You normally want operations on cin / cout to block. But again, blocking vs. non-blocking I/O has nothing to do with whether cin / cout are tied.

and buffer gets flushed properly when I am not using std::endl. Does the use of "\\n" automatically handles it?

Outputting '\\n' only flushes the buffer if the stream is in line-buffered mode. cout is automatically put in line-buffered mode if output goes to a terminal; otherwise it is block buffered (ie it only gets flushed when it runs full).

In a programming competition cout usually goes to a pipe or log file, so it will be block buffered and '\\n' doesn't cause a flush. However, in that situation it also doesn't matter whether prompts are displayed before input is read (which is the normal use case for tied cin / cout ). Just make sure you produce the right output and let the I/O library worry about buffering. The buffer is automatically flushed when it runs full, when the stream is closed, and when your program exits. No output is lost (unless your program crashes, but then you have other things to worry about).

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