Multiple Lines
std::cout doesn't start a new line by itself. It prints exactly what you send to it, and the next output continues right after it, on the same line:
std::cout << "Good";
std::cout << "morning";This prints:
GoodmorningThere are two ways to end a line:
- send
std::endlto the output, as in the previous exercise, - or write
\nat the end of the text. A backslash followed by the lettern(new line) isn't printed; it means the end of the line.
std::cout << "First line" << std::endl;
std::cout << "Second line\n";This prints:
First line
Second lineBoth end the line in the same way, and you'll see both in this course. \n can be anywhere in the text, even several times: std::cout << "One\nTwo\n"; prints two lines.
One std::cout statement can also send several things to the output in a row, each after its own <<. So this statement prints two lines too:
std::cout << "First line" << std::endl << "Second line" << std::endl;Usually, though, it's clearer to write each line of output as its own statement, on its own line of code.
To print an empty line, end a line without printing anything on it: std::cout << std::endl; or std::cout << "\n";.
Instructions
- 1
Run the program: both texts are printed on one line. Fix it by ending the first line with
std::endl: after the text"I'm learning C++", add<< std::endl. The program then prints:I'm learning C++ It's awesome - 2
End the second line in the other way: at the end of the text
"It's awesome", write\n. Then, below it, add a statement that prints a third line, so that the program prints:I'm learning C++ It's awesome I'll be a programmer!