当我可以使用换行符时,为什么要使用endl ?
Why use endl when I can use a newline character?
当我可以使用n
时,是否有理由使用endl
与cout
?我的c++书上说要使用endl,但我不明白为什么。n
不像endl
那样被广泛支持,还是我错过了什么?
endl
将'n'
追加到流, 在流上调用flush()
。所以
cout << x << endl;
等价于
cout << x << 'n';
cout.flush();
流可以使用内部缓冲区,该缓冲区在流刷新时实际流化。在cout
的情况下,您可能不会注意到差异,因为它以某种方式与cin
同步(绑定),但对于任意流,例如文件流,您将注意到多线程程序中的差异,例如。
这里有一个关于为什么需要刷新的有趣讨论
endl
不仅仅是n
字符的别名。当您向cout
(或任何其他输出流)发送某些内容时,它不会立即处理和输出数据。例如:
cout << "Hello, world!";
someFunction();
在上面的例子中,有一些的机会,函数调用将在输出被刷新之前开始执行。使用endl
可以强制在执行第二条指令之前进行刷新。您还可以使用ostream::flush
函数来确保。
endl是函数而不是关键字。
#include <iostream>
int main()
{
std::cout<<"Hello World"<<std::endl; //endl is a function without parenthesis.
return 0;
}
要了解endl的图片,首先需要了解"指针指向函数"的主题。
看这段代码(用C写的)
#include <stdio.h>
int add(int, int);
int main()
{
int (*p)(int, int); /*p is a pointer variable which can store the address
of a function whose return type is int and which can take 2 int.*/
int x;
p=add; //Here add is a function without parenthesis.
x=p(90, 10); /*if G is a variable and Address of G is assigned to p then
*p=10 means 10 is assigned to that which p points to, means G=10
similarly x=p(90, 10); this instruction simply says that p points to add
function then arguments of p becomes arguments of add i.e add(90, 10)
then add function is called and sum is computed.*/
printf("Sum is %d", x);
return 0;
}
int add(int p, int q)
{
int r;
r=p+q;
return r;
}
编译此代码并查看输出。
回到主题…
#include <iostream>
//using namespace std;
int main()
{
std::cout<<"Hello World"<<std::endl;
return 0;
}
iostream文件包含在这个程序中,因为cout对象的原型存在于iostream文件中,而STD是一个命名空间。使用它是因为cout和endl的定义(库文件)存在于命名空间std中;或者您也可以在顶部使用"using namespace std",这样您就不必在每个cout或endl之前写"std::coutn<<....."。
当你写没有括号的endl时,你把函数endl的地址给cout,然后调用endl函数并改变行。背后的原因是
namespace endl
{
printf("n");
}
结论:c++的背后,C的代码是工作的
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为什么在popback()操作之后,它仍然打印完整的矢量
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 为什么会发生堆损坏
- 为什么使用 "this" 指针调用派生成员函数?
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 为什么比较运算符如此快速
- std::cout << glGetString(GL_RENDER) << std::endl;抛出错误但不GL_Renderer或GL_Verision,我不知道为什么?
- 为什么模板运算符<<不推导出 std::endl?
- 库特 << 2[ "abc" ] << endl;为什么它有效?这是哪种语法?
- 为什么将 std::endl 与 ostringstream 一起使用会影响输出速度
- 为什么在语句"std::cout << std::endl;"中使用时需要命名空间限定,给定依赖于参数的查找?
- 为什么要编译endl(std::cout)
- 为什么'QTextStream(stdout) << endl;'编译,而'QTextStream(stdout)
- 为什么"std::cout << myVector[x][x] << std::endl"会产生下标错误?
- 为什么它没有endl就包装了;
- 如果std::endl是一个函数,为什么不使用括号?
- 当我可以使用换行符时,为什么要使用endl ?