Return char1 + char2? Is it impossible?

I am trying to return a string from a function. Which basically adds a few characters and returns a string representation.

string toString() { char c1, c2, c3; // some code here return c1 + c2; // Error: invalid conversion from `char' to `const char*' } 

booleans can be returned, such as return c1 == 'x'. Is it impossible to return string values? I know this is possible like this:

 string result; result.append(c1, c2); return result; 

I am new to C ++, so I thought there should be a more elegant solution.

+4
source share
6 answers

No, you cannot do this, because adding two char together will not give you a string. It gives you another char; in this case, 'a'+'b' really gives you '├' (on Windows with the standard CP_ACP code page). char is an ordinal type, such as integers, and the compiler knows how to add them in the simplest ways. Strings are a completely different beast.

You can do this, but you must be explicit:

 return string(1, c1) + string(1, c2) 

This will build two temporary lines, each of which is initialized with one repetition of the character passed as the second parameter. Since operator+ defined so that strings are a concatenation function, now you can do what you want.

+9
source

char types in C ++ (and also in C) are integer types. They behave like whole types. Just like when you write 5 + 3 in your code, you expect to get integral 8 as the result (not the string "53" ), when you write c1 + c2 in your code above, you should expect to get the integral result - arithmetic sum of c1 and c2 .

If you really want to combine two characters to form a string, you have to do it differently. There are many ways to do this. For example, you can create a C style string

 char str[] = { c1, c2, `\0` }; 

which will be implicitly converted to std::string on

 return str; 

Or you can immediately build std::string (which can also be done in several ways).

+7
source

You can convert each char to a string and then use +:

 return string(1, c1)+string(1, c2); 

Alternatively, the line has an operator overload + for working with characters, so you can write:

 return string(1, c1) + c2; 

No matter which method you choose, you will need to convert the integral char type to a C-style string ( char* ) or a C ++ style string ( std::string ).

+4
source
 return string(1, c1) + c2; 

This creates a 1-character string containing c1, then adds (overloads for concatenation) c2 (creates another string), and then returns it.

+2
source

No, they just add character codes. You need to convert them to strings.

+1
source

You need to create a string of characters.
And then return the string (actually a copy of the string)

0
source

Source: https://habr.com/ru/post/1305509/


All Articles