Lesson 2: Printing Several Things Together
In the previous lesson we printed a single string. Now we'll learn one new thing: you can chain several << on the same line to print text and numbers together. In C you needed %d and %s in printf; in C++ you just put << before each item, and that's it. That's all for this lesson.
Each << is 'and then': std::cout << "Age: " << age << "\n"; reads 'print Age:, and then age, and then a new line'.
- chaining
- Joining several items in one print statement with multiple <<, e.g. std::cout << a << b << c;
- printing a variable
- In C++ you put the variable name after << and its value is printed; no need for %d as in printf.
- printing an expression
- You can print the result of a computation directly: std::cout << age + 1; prints the sum.