Printing Variables
A number on its own doesn't say much in the output. But with <<, you can send several parts to the output one after another, text and variables, and print a whole sentence:
int age = 15;
std::cout << "I am " << age << " years old.\n";This prints:
I am 15 years old.std::cout prints the parts from left to right: text in quotes exactly as it's written, and for a variable without quotes, its value. So watch the quotes: std::cout << "age"; prints the word age, not the value of the variable.
<< doesn't add any spaces between the parts. You have to write the spaces yourself, inside the quotes. That's why "I am " has a space at the end and " years old.\n" at the start. Without them, the words stick to the number:
int age = 15;
std::cout << "I am" << age << "years old.\n";This prints:
I am15years old.One statement can print several variables:
int height = 168;
int weight = 55;
std::cout << "Height: " << height << " cm, weight: " << weight << " kg\n";This prints:
Height: 168 cm, weight: 55 kgInstructions
- 1
Run the program. It prints
Home3. Change the text in quotes so that the program printsHome: 3. - 2
Below it, print the variable
awaythe same way:Away: 1 - 3
Finally, print this line with one
std::coutstatement. Don't write the numbers 90, 3 and 1 into the text; take them from the variables:Score after 90 minutes: 3:1