Because that's not how to use streams, or strings.
The +
operator is for:
- adding two numbers together, or
- concatenating two
std::string
s together.
Here you have a string literal and a number. The +
operator is not compatible with those.
(What you actually end up doing is "adding" 10
to the pointer representing the string literal; as it happens, because your string is ten characters long, that leaves the pointer exactly where your string literal's NULL terminator is, so it is like trying to print ""
.)
The correct approach, as you have yourself found via the second example, is to use the stream's <<
operator again.
cout << "Hello C++ " << x;