“ std :: endl”与“ \n” [英] "std::endl" vs "\n"

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

问题描述

许多C ++书籍都包含这样的示例代码...

Many C++ books contain example code like this...

std::cout << "Test line" << std::endl;

...所以我也总是这样做。但是我从工作的开发人员那里看到了很多这样的代码:

...so I've always done that too. But I've seen a lot of code from working developers like this instead:

std::cout << "Test line\n";

是否有技术上的原因要优先于另一个,还是仅仅是编码风格的问题?

Is there a technical reason to prefer one over the other, or is it just a matter of coding style?

推荐答案

不同的行尾字符无关紧要,假设文件以文本模式打开,这就是您所需要的得到,除非您要求二进制。

The varying line-ending characters don't matter, assuming the file is open in text mode, which is what you get unless you ask for binary. The compiled program will write out the correct thing for the system compiled for.

唯一的区别是 std :: endl 刷新输出缓冲区,然后' \n'不会。如果您不希望频繁刷新缓冲区,请使用’\n’。如果这样做(例如,如果要获取所有输出,并且程序不稳定),请使用 std :: endl

The only difference is that std::endl flushes the output buffer, and '\n' doesn't. If you don't want the buffer flushed frequently, use '\n'. If you do (for example, if you want to get all the output, and the program is unstable), use std::endl.

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

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