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

Text and Numbers

You can send both text and numbers to the output. Text goes in double quotes, numbers are written without them. Decimal numbers are written with a dot: 3.5.

std::cout << 42 << "\n";
std::cout << 3.5 << "\n";

This prints:

42
3.5

After the numbers, we sent the text "\n", which contains only the end of the line.

The difference between text and a number is that C++ can calculate with numbers. It works out an expression without quotes and prints the result, while text in quotes is printed exactly as it is:

std::cout << 5 + 3 << "\n";
std::cout << "5 + 3" << "\n";

This prints:

8
5 + 3

You'll learn more about calculating in the next lesson.

You can mix text and numbers in one statement as you like; just write << before each part:

std::cout << "The game has " << 12 + 8 << " levels." << std::endl;

This prints:

The game has 20 levels.

<< doesn't put any spaces between the parts. You have to write the spaces you want in the output inside the quotes. A common mistake:

std::cout << "The game has" << 12 + 8 << "levels." << std::endl;

This prints:

The game has20levels.

Always put text in double quotes ". Single quotes, such as 'A', mean something else in C++: a single character, as you'll see in the next lesson.

Instructions

  1. 1

    The second statement prints the text 27 + 2. Remove the quotes, so that C++ adds up the numbers and prints 29.

  2. 2

    Now turn the result into a whole sentence. Change the second statement, so that the program prints:

    27 students and 2 teachers are going on the trip.
    That's 29 people in total.

    Let C++ keep calculating the 29: join the text and the calculation with <<, and don't forget the spaces in the text.

Back

4/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.