Reputation: 73
Can you explain me the Exercise 1-2 from accelerated c++?
int main()
{
const std::string exclam = "!";
const std::string message = "Hello" + ", world" + exclam;
std::cout << message << std::endl;
}
Why is this not correct? Changing the variable with "Hello" works fine.
Is it because of the fact that the operator + is right-associative?
Upvotes: 1
Views: 1208
Reputation: 1025
Adding to the explanation of @songyuanyao, you can do this either by using the +
operator of std::string
:
const std::string left = "Hello ";
const std::string right = "World";
const std::string point = "!";
std::cout << left + right + point << std::endl;
or by manipulating the output directly with std::cout
:
const std::string left = "Hello";
const std::string right = "World";
const std::string point = "!";
std::cout << left << " " << right << point << std::endl;
Or by using the printf
function (don't forget to #include <stdio.h>
):
const std::string left = "Hello";
const std::string right = "World";
const std::string point = "!";
printf("%s %s%s\n", left.c_str(), right.c_str(), point.c_str());
Look at this post if you want to know what the c_str()
is about.
Upvotes: 1
Reputation: 172864
The associativity of operator+
is left-to-right. Then "Hello" + ", world" + exclam
is interpreted as ("Hello" + ", world") + exclam
while "Hello" + ", world"
is invalid. "Hello"
and ", world"
are const char[]
s and could decay to pointer as const char*
which can't be added.
Using std::string
instead of c-style string, or changing the code to "Hello" + (", world" + exclam)
works because there's operator+
for std::string
which could accept two std::string
s or a std::string
and a c-style string (as either the 1st or 2nd operand), and it returns std::string
which could be added further.
Upvotes: 3