C++ Output

C++ Output (Print Text)

In C++, you can output data to the screen using the cout object along with the << operator.

Printing Text

To print text, you place the text inside double quotes:

Example

#include <iostream>
using namespace std;

int main() { cout << "Learning C++ is fun!"; return 0; }

You can use as many cout objects as you want. However, they do not automatically insert a new line at the end.

Adding New Lines

To insert a new line, you can use the \n character or the endl manipulator.

Example

#include <iostream>
using namespace std;

int main() { cout << "Hello World! \n"; cout << "I am learning C++." << endl; cout << "This is on a new line."; return 0; }

Using \n is slightly faster, but endl is also very common because it flushes the output stream.


Exercise

?

Which of the following is used to insert a new line in C++ output?