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.5After 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 + 3You'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
The second statement prints the text 27 + 2. Remove the quotes, so that C++ adds up the numbers and prints 29.
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.
Start programming for free
3/6