C++ new line
In C++, there are several ways to insert a new line in a stream, such as std::cout
or std::ofstream
. Here are a few examples:
-
Using the
\n
escape sequence:std::cout << "Hello, world!\n";
This will output "Hello, world!" followed by a new line.
-
Using the
std::endl
manipulator:std::cout << "Hello, world!" << std::endl;
This will output "Hello, world!" followed by a new line, and also flush the buffer.
-
Using the
std::endl
manipulator with a variable:int x = 5; std::cout << "Hello, world!" << std::endl << x << std::endl;
This will output "Hello, world!" followed by a new line, then the value of
x
followed by another new line. -
Using the
std::endl
manipulator with a string:std::string str = "Hello, world!"; std::cout << str << std::endl;
This will output the contents of the string followed by a new line.
-
Using the
std::endl
manipulator with a formatted string:std::cout << std::fixed << std::setprecision(2) << 3.14 << std::endl;
This will output the value of
3.14
with two decimal places followed by a new line.
Note that std::endl
is a manipulator that inserts a new line and also flushes the buffer. If you want to insert a new line without flushing the buffer, you can use \n
instead.