I want to concatenate more characters and strings to an existing string in c++

160 Views Asked by At
string s;
s += "#" + ',';  //give error
s += "#" + ",";  //give error
s += to_string(23) + ',';   //no error

What is the proper way to concatenate new characters and strings to an existing string using + operator and when will it throw error? Can someone also shed light how append() and push_back() are different from "+" and which is the most optimal way?

3

There are 3 best solutions below

2
user12002570 On

Case 1

Here we consider the statement s += "#" + ',';.

The problem is that operator+ has higher precedence than operator+=. This means that s += "#" + ',' is equivalent to writing

s += ("#" + ','); //same as s += "#" + ','

Now, "#" is a string literal of type const char [2] while ',' is a character literal of type char. So basically, in this case you're trying to add a string literal to a char. Now, when you do this, string literal decays to a const char* and the character literal is promoted to int.

Essentially, this adds a const char* to an int. The result of this is used as an operand of +=.

More about this can be read at C++ Adding String Literal to Char Literal


Case 2

Here we consider the statement s += "#" + ",";.

In this case also the statement s += "#" + ","; is equivalent to writing:

s += ("#" + ","); //same as s += "#" + ","

due to operator precedence.

But in this case both the operand to operator+ are of type const char [2].

So essentially, you're trying to add two string literals here. But there is no overloaded operator+ that takes two string literals or const char* so this gives the mentioned error:

 error: invalid operands of types 'const char [2]' and 'const char [2]' to binary 'operator+'

Solution

There are several ways to solve this one of which include to add suffix s after the string literal as shown below:

using namespace std::string_literals;
s += "#"s + ","s;  //works correctly now

Another way is to explicitly write std::string("#").

0
Serge Ballesta On

C++ now(*) allows litteral strings.

using namespace std::string_literals;

string s = "foo";
s += "#"s + ","s;

Not only this code raises no error, but it produces the expected output.


(*) Since C++14, according to cppreference

0
JeJo On

Which is the most optimal way?

If you mean by optimal <-> convenience to do the concatenation of chars and/or string literals and/or std::string, is a variadic template function that does it as follows:

template<typename... Args>
std::string concatenate(Args&&... args) {
   return (std::string{} + ... + std::forward<Args>(args)); // require C++17
}

See a live demo

You don't need to worry now about what you pass/ type (i.e. const char, char[], char or std::string). The function will return the concatenated string for you.

char arr[]{ "..." };
std::cout << concatenate('H', 'e', 'l', 'l', 'o', " World", "!"s, arr); // prints Hello World!...