当我可以只使用
endl
时,是否有理由将 cout
与 \n
一起使用?我的 C++ 书上说要使用 endl,但我不明白为什么。 \n
是否没有像 endl
那样得到广泛支持,或者我错过了什么?
endl
将 '\n'
附加到流 ,并且 在流上调用 flush()
。所以
cout << x << endl;
相当于
cout << x << '\n';
cout.flush();
流可以使用内部缓冲区,当流被刷新时,该缓冲区实际上会被流式传输。对于
cout
,您可能不会注意到差异,因为它以某种方式与 cin
同步(tied),但对于任意流(例如文件流),您会注意到多线程程序中的差异,例如.
这里有一个关于为什么需要冲洗的有趣讨论。
endl
不仅仅是 \n
字符的别名。当您将某些内容发送到 cout
(或任何其他输出流)时,它不会立即处理和输出数据。例如:
cout << "Hello, world!";
someFunction();
在上面的示例中,函数调用有可能在输出刷新之前开始执行。使用 endl
可以强制在执行第二条指令之前进行刷新。您还可以使用
ostream::flush
功能来确保这一点。
#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”,这样你就不必写“std::coutn
当您编写不带括号的 endl 时,您将函数 endl 的地址赋予 cout,然后调用 endl 函数并更改行。 这背后的原因是<<....." before each cout or endl.
namespace endl
{
printf("\n");
}
结论:在 C++ 背后,C 代码正在运行。