使用cout
时,是否有理由使用endl
而不是直接使用\n
?我的C++书上说要使用endl
,但我不明白为什么。是因为\n
的支持不如endl
广泛,还是我漏掉了什么重要的东西?
使用cout
时,是否有理由使用endl
而不是直接使用\n
?我的C++书上说要使用endl
,但我不明白为什么。是因为\n
的支持不如endl
广泛,还是我漏掉了什么重要的东西?
endl
将'\n'
附加到流中并调用流上的flush()
。所以
cout << x << endl;
等同于
cout << x << '\n';
cout.flush();
cout
,您可能不会注意到差异,因为它与cin
有一定的同步(绑定),但对于任意流,例如文件流,在多线程程序中您会注意到差异。'\n'
会自动转换为相应的字符。因此,是的,由于endl
附加了一个'\n'
,这种情况正在发生。但这不仅适用于endl
。 - Chad La Guardiaendl
不仅仅是 \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;
}
#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");
}
endl
。请参见此答案和评论。 - ildjarn'\n'
和std::endl
没有区别(区别在于flush
)。 (Mac平台从OSX开始是基于Unix的,使用'\n'
标记行尾。) - Keith Thompsonstd::cerr
很容易被重定向到与std::cout
不同的文件中。 - Keith Thompson\endl
),以及仅使用\n
的情况。http://programmers.stackexchange.com/questions/185064/using-a-stream-manipulator-endl-or-a-newline-escape-character-n - Ruchir