The cout object, together with the << operator, is used to output values/print text:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
return 0;
}
You can add as many cout objects as you want. However, note that it does not insert a new line at the end of the output:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!";
cout << "I am learning C++";
return 0;
}
To insert a new line, you can use the \n character:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n";
cout << "I am learning C++";
return 0;
}
Tip: Two \n characters after each other will create a blank line:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World! \n\n";
cout << "I am learning C++";
return 0;
}
Another way to insert a new line, is with the endl manipulator:
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!" << endl;
cout << "I am learning C++";
return 0;
}
Both \n and endl are used to break lines. However, \n is most used.
But what is \n exactly?
The newline character (\n) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.
You have already learned that cout is used to output (print) values. Now we will use cin to get user input.
cin is a predefined variable that reads data from the keyboard with the extraction operator (>>).
In the following example, the user can input a number, which is stored in the variable x. Then we print the value of x:
int x;
cout << "Type a number: "; // Type a number and press enter
cin >> x; // Get user input from the keyboard
cout << "Your number is: " << x; // Display the input value
Watch the 10th part of this video
Write a program that displays your favorite poem. Use an appropriate escape sequence for the line breaks. If you don't have a favorite poem, you can borrow this one by Ogden Nash:
Candy is dandy,
But liquor is quicker.