Concatenating strings doesn't work as expected

C++Operator KeywordString ConcatenationStdstringStandard Library

C++ Problem Overview


I know it is a common issue, but looking for references and other material I don't find a clear answer to this question.

Consider the following code:

#include <string>

// ...
// in a method
std::string a = "Hello ";
std::string b = "World";
std::string c = a + b;

The compiler tells me it cannot find an overloaded operator for char[dim].

Does it mean that in the string there is not a + operator?

But in several examples there is a situation like this one. If this is not the correct way to concat more strings, what is the best way?

C++ Solutions


Solution 1 - C++

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world";

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world";

Solution 2 - C++

std::string a = "Hello ";
a += "World";

Solution 3 - C++

I would do this:

std::string a("Hello ");
std::string b("World");
std::string c = a + b;

Which compiles in VS2008.

Solution 4 - C++

std::string a = "Hello ";
std::string b = "World ";
std::string c = a;
c.append(b);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndryView Question on Stackoverflow
Solution 1 - C++Konrad RudolphView Answer on Stackoverflow
Solution 2 - C++SvisstackView Answer on Stackoverflow
Solution 3 - C++graham.reedsView Answer on Stackoverflow
Solution 4 - C++Teodor PripoaeView Answer on Stackoverflow