std :: endl和'\ n'有什么区别 [英] What's the difference between std::endl and '\n'
问题描述
我已经读到了std::endl
和'\n'
之间的区别是std::endl
刷新了缓冲区,而'\n'
没有.但是,据我所知,Linux上的stdout
仍然是行缓冲的,这是否意味着std::cout << ... << std::endl
与std::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::cout
和std::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屋!