Home  >  Article  >  Backend Development  >  The role of endl in c++

The role of endl in c++

下次还敢
下次还敢Original
2024-04-26 20:00:24301browse

C in endl is a stream insertion operator, its function is as follows: insert a newline character into the output stream. Flush the output stream. It is generally recommended to use endl instead of the newline character '\n' as it ensures that the output is flushed immediately, avoiding data loss or ordering issues.

The role of endl in c++

The role of endl in c

endl is a stream insertion operator in C, used to output Insert a newline character into a stream (such as cout).

Specific effect:

  • It will insert a newline character ('\n') into the output stream, causing the current line to end and a new line to start. .
  • It can also flush the output stream, immediately writing the data in the buffer to the output device (such as the monitor).

Differences from '\n':

endl differs from the newline character '\n' because it performs the following additional operations:

  • Refresh the output stream
  • Raise the stream status flag (ie clear the stream error flag)

Normally, it is recommended to use endl instead of '\n', Because it ensures that output is flushed immediately, avoiding data loss or sequencing issues.

Example:

<code class="cpp">#include <iostream>

using namespace std;

int main() {
  cout << "This is line 1" << endl;
  cout << "This is line 2";

  return 0;
}</code>

Output:

<code>This is line 1
This is line 2</code>

In the above example, endl is used to insert a newline character after the first line, thus starting new line. Since endl flushes the output stream, the second line is immediately written to the display.

The above is the detailed content of The role of endl in c++. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn