std :: endl和'\ n'有什么区别 [英] What's the difference between std::endl and '\n'

查看:117
本文介绍了std :: endl和'\ n'有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经读到了std::endl'\n'之间的区别是std::endl刷新了缓冲区,而'\n'没有.但是,据我所知,Linux上的stdout仍然是行缓冲的,这是否意味着std::cout << ... << std::endlstd::cout << ... << '\n'相同?

I've read the difference between std::endl and '\n' is that std::endl flushes the buffer and '\n' doesn't. However, as far as I know stdout on linux is line-buffered anyway, so does it mean that std::cout << ... << std::endl is the same as std::cout << ... << '\n'?

推荐答案

std::ostream os;

os << std::endl; // more concise

os << '\n' << std::flush; // more explicit about flushing

这两行效果完全相同.

手动冲洗通常是浪费时间:

The manual flushing is often a waste of time:

  • 如果输出流是行缓冲的,则std::cout应该是这种情况,如果它连接到交互式终端,并且实现可以检测到该结果,然后打印\n已经刷新.

  • If the output stream is line-buffered, which should be the case for std::cout if it connects to an interactive terminal and the implementation can detect that, then printing \n already flushes.

如果输出流与您随后直接从中读取的输入流配对(std::coutstd::cin已配对),则读取已刷新.

If the output stream is paired with an input stream you read from directly afterwards (std::cout and std::cin are paired), then reading already flushes.

如果您没有人等待数据到达其目的地,则刷新将再次浪费.

If you nobody waits for the data to arrive at its destination, flushing is again just going to waste.

这篇关于std :: endl和'\ n'有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆