This works with std::string
std::string class::something(char* input) {
std::string s(input);
s = "hai! " + s;
return s;
}
But fails if I try the same thing with wstring
std::wstring class::something(wchar_t* input) {
std::wstring s(input);
s = "hai! " + s;
return s;
}
How do I do the same thing with std::wstring?
String overview std::string is used for standard ascii and utf-8 strings. std::wstring is used for wide-character/unicode (utf-16) strings. There is no built-in class for utf-32 strings (though you should be able to extend your own from basic_string if you need one).
This function is used to convert the numerical value to the wide string i.e. it parses a numerical value of datatypes (int, long long, float, double ) to a wide string. It returns a wide string of data type wstring representing the numerical value passed in the function.
Simply use the c_str function of std::w/string . Save this answer.
The problem here is types. A wstring isn't a string, but a quoted string constant is related to it (it is generally a const char*), so
s = "hai! " + s;
is actually a problem.
The value "hai! " is of type const char*, not type const wchar_t*. Since const char* is a basic type, it's searching for a global operator+ that operates const char* and wstring, which doesn't exist. It would find one for const wchar_t* and wstring, because std::basic_string<T>, the template underyling type for both string and wstring (using char and wchar_t as the type parameter, respectively) also creates template methods for operator+ (const T*& s1, const basic_string<T> s2) so that addition can work.
Therefore, you need to make "hai! " a wstring:
std::wstring class::something(wchar_t* input){
std::wstring s(input);
s = L"hai! " + s;
return s;
}
The L prefix on a string constant, in Visual C++, defines it to be "long", and therefore a wstring. wstring is actually basic_string<wchar_t>, which is, because of the behavior of C++ templates, a completely different type from basic_string<char> (a std::string), so you can't combine the two.
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