当我可以使用换行符时,为什么要使用endl ?

Why use endl when I can use a newline character?

本文关键字:endl 为什么 我可以 可以使 换行符      更新时间:2023-10-16

当我可以使用n时,是否有理由使用endlcout ?我的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的代码是工作的