0

If I have this below code -

string str;
wstring wstr;

for (char x : str)
{
    wstr += x;
}

Is this line wstr += x wrong? Do I need some conversion function to convert char x to wchar_t to be stored in wstr? If yes, which conversion function do I need?

Edit - I have gone through the linked answers, it mentions about converting the array of wchar_t and char -> for that for sure conversion functions are needed but my question specifically asks if a char -> wchar_t would need conversion function

user123456
  • 13
  • 5
  • `wstr.push_back(x);` – Eljay Dec 07 '22 at 02:54
  • What do you expect `wstr += x` to achieve? If you look at the documentation, does `std::wstring` (or `std::basic_string`, since both `std::string` and `std::wstring` are actually specialisations of `basic_string`) provide an `operator+=()` that does what you expect? – Peter Dec 07 '22 at 02:57
  • @Eljay does push_back already converts the char x to wchar_t for me? – user123456 Dec 07 '22 at 02:57
  • @Peter this is like a short snippet of a bigger code, but x is char of 1 byte while i am storing it in wstr for which each character is 2 bytes, since I am storing a smaller char (1byte) in a bigger character wchar_t (2bytes) would any conversion be needed to convert the char to wchar_t? – user123456 Dec 07 '22 at 03:00
  • `push_back()` does not, in itself, do any conversion. But `std::wstring` has a `push_back()` which accepts an argument of type `wchar_t`. And the statement `wstr.push_back(x)` will implicitly convert `x` to `wchar_t` if that is permitted, and then pass that converted value to `push_back()`. – Peter Dec 07 '22 at 03:00
  • @Peter Got it, thank you, does the operator+() -> also implicitly convert x from char to wchar_t? – user123456 Dec 07 '22 at 03:03
  • You're thinking about this too much. Yes, to append characters to a `wstring`, it is necessary for those characters to be converted to `wchar_t`. But there are operations which will do that implicitly, due to rules of the language (e.g. if a `char` is passed as an argument to a function that expects a `wchar_t`, then that `char` will be converted implicitly). In your case, you could simply do `wstr.append(str.begin(), std.end())` and eliminate the loop entirely. – Peter Dec 07 '22 at 03:06
  • I didn't test it; I presume it will convert the char to wchar_t. For ASCII range `char`, it should work. If the char is a UTF-8 encoding, it will not *transcode* into a UTF-16 encoding. – Eljay Dec 07 '22 at 13:25

0 Answers0