In the C++ world, you can only concatenate string classes, like std::string. And there is no automatic "to string" for ints, etc.
A literal string is seen as a pointer to an array of chars. And adding an integer to a pointer advances it by sizeof(type). That is ptr + 3 is the same as ptr[3]. So...
cout << "Come in #" + 3 << endl;
doesn't output "Come in #3", it outputs "e in #". As you told the compiler to advance the pointer by 3 chars along the string.
If you want to use concatenation with string literals, you will have to use strcat into a buffer.
If your compiler also support itoa(), you can then do:
1 2 3 4 5 6 7 8
|
char buffer[256] = {0); // zero buffer
char temp[32] = {0); // for string conversion
strcat(buffer, "There are ");
strcat(buffer, itoa(hours, temp, 10));
strcat(buffer, "hours in ");
strcat(buffer, itoa(years, temp, 10));
strcat(buffer, "!");
cout << buffer<< endl;
|
But if your compiler doesn't provide itoa, then you need to use sprintf() or ostringstream (preferred in the C++ world). But if you are using an ostream for the conversion, and then writing the final string to cout, another ostream, why not just do as Robertoplusplus suggested. This is the idiomatic C++ way to do thing.
Note that it still doesn't work if the values you are outputting are strings:
1 2 3 4
|
const char fruit[] = "lemon";
const char fruit_color[] = "yellow";
cout << "The " << fruit << " is a " << fruit_color << " fruit." << endl;
|
But it you use std::string instead, and avoid trying to join two string literals, then it does work:
1 2 3 4
|
const string fruit = "lemon";
const string fruit_color = "yellow";
cout << "The " + fruit + " is a " + fruit_color + " fruit." << endl;
|
But this isn't idomatic C++. The C++ way is to use <<.
cout << "The " << fruit << " is a " << fruit_color << " fruit." << endl;
I use string concatenation (using std::string) when I need to build up a string from substrings for use other than output. If I need to build a string which includes int values, etc then I use ostringstream to build the string using <<, and then the ostringstream::str() to obtain the final string.