문제

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).

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

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

Alternately, string has the + operator overload to work with characters, so you can write:

return string(1, c1) + c2;

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

return string(1, c1) + c2;

This constructs a 1-character string, containing c1, then adds (overloaded to concatenate) c2 (creating another string), then returns it.

No, they just adds up the character codes. You need to convert them to strings.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top