I'm trying to return a string from a function. Which basically adds some chars together and return the string representation.
string toString() {
char c1, c2, c3;
// some code here
return c1 + c2; // Error: invalid conversion from `char' to `const char*'
}
it is possible to return boolean values like return c1 == 'x'. Isn't it possible to return string values? I know that it is possible to it like this:
string result;
result.append(c1, c2);
return result;
I'm new to C++ so I thought that there must be more elegant solution around.
No, you can't do that because adding two char's together doesn't give you a string. It gives you another char; in this case 'a'+'b'
actually gives you '├'
(on Windows with the standard CP_ACP code page). Char is an ordinal type, like integers and the compiler only knows how to add them in the most basic of ways. Strings are a completely different beast.
You can do it, but you have to be explicit:
return string(1, c1) + string(1, c2)
This will construct two temporary strings, each initialized to one repetition of the character passed as the second parameter. Since operator+
is defined for strings to be a concatenation function, you can now do what you want.
char
types in C++ (as well as in C) are integral types. They behave as integral types. Just like when you write 5 + 3
in your code, you expect to get integral 8
as the result (and not string "53"
), when you write c1 + c2
in your code above you should expect to get an integral result - the arithmetic sum of c1
and c2
.
If you actually want to concatenate two characters to form a string, you have to do it differently. There are many ways to do it. For example, you can form a C-style string
char str[] = { c1, c2, `\0` };
which will be implicitly converted to std::string
by
return str;
Or you can build a std::string
right away (which can also be done in several different ways).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With