Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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:

Goodmorning

There are two ways to end a line:

  • send std::endl to the output, as in the previous exercise,
  • or write \n at the end of the text. A backslash followed by the letter n (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 line

Both 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. 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. 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!
Back

2/8

  1. 1. Your First Program
  2. 2. Multiple Lines
  3. 3. Quiz: New Lines
  4. 4. Text and Numbers
  5. 5. Comments
  6. 6. Reading Errors
  7. 7. Quiz: Spot the Mistake
  8. 8. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.