Programing

개행 문자를 사용할 수 있는데 왜 endl을 사용합니까?

lottogame 2020. 12. 31. 07:54
반응형

개행 문자를 사용할 수 있는데 왜 endl을 사용합니까?


이 질문에 이미 답변이 있습니다.

그냥 사용할 수있을 때 endl와 함께 사용하는 이유가 있나요? 내 C ++ 책은 endl을 사용하라고 말했지만 그 이유를 모르겠습니다. 되어 널리 등으로 사용할 수 없습니다 , 또는 내가 뭔가를 놓친 게 뭐죠?cout\n\nendl


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의 그림을 이해하려면 먼저 "Pointer to Functions"주제에 대해 이해해야합니다.

이 코드를보세요 (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 file is included in this program because the prototype of cout object is present in iostream file and std is a namespace. It is used because defination(library files) of cout and endl is present in namespace std; Or you can also use "using namespace std" at top, so you don't have to write "std::coutn<<....." before each cout or endl.

when you write endl without paranthesis then you give the address of function endl to cout then endl function is called and line is changed. The reason Behind this is

namespace endl
{
printf("\n");
}

Conclusion: Behind C++, code of C is working.

ReferenceURL : https://stackoverflow.com/questions/7324843/why-use-endl-when-i-can-use-a-newline-character

반응형