String concatenation is not working properly

I know this is a common problem, but looking at the links and other materials, I do not 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 that it cannot find the overloaded operator for char[dim] .

Does this mean that there is no + operator in the string?

But in a few examples there is such a situation. If this is not the right way to concatenate more lines, what is the best way?

+81
c ++ stdstring string-concatenation operator-keyword standard-library
Nov 29 '10 at 14:25
source share
4 answers

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

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

This does not work, because for C ++ it is like trying to add two char pointers. Instead, you need to convert at least one of the char* literals to std::string . Either you can do what has already been posted in the question (as I said, this code will work), or you will do the following:

 std::string c = std::string("hello") + "world"; 
+150
Nov 29 '10 at 14:29
source share
 std::string a = "Hello "; a += "World"; 
+47
Nov 29 '10 at 14:28
source share

I would do this:

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

What compiles in VS2008.

+5
Nov 29 '10 at 14:28
source share
 std::string a = "Hello "; std::string b = "World "; std::string c = a; c.append(b); 
+5
Nov 29 '10 at 14:29
source share



All Articles