Search code examples
c++typeswchar-t

Changing type of char using wchar_t used not so like L


In my code I tried to create massive of 4 bite chars, where every char contain a Cyrillic letter.

  wchar_t OUT_STRING[4] = { L'т',L'л',L'о',L'р' };

All in normal with this and I have expected output. It's only test, in real I need to convert element from string to the same type like in OUT_STRING; I tried to use something like this:

 wchar_t OUT_STRING[4] = { (wchar_t)'т',L'л',L'о',L'р' };

But it didn't work and in output I have a rectangle.


Solution

  • I think you want to pass in a string using std::string in UTF-8 encoding and process it one character at a time, each time converting the single character to a wide character string of length 1 so that you can pass it to TTF_SizeUNICODE, and TTF_RenderUNICODE_Blended.

    I will demonstrate the relevant string conversion code.

    Here is a test function that expects a null-terminated wide character string with just one character in it. The body of main shows how to convert a UTF-8 string to UTF-16 (using codecvt_utf8_utf16) and how to convert a single character to a string (using std::wstring(1, ch))

    #include <string>
    #include <codecvt> 
    #include <iostream>
    
    void test(const wchar_t* str) {
        std::cout << "Number of characters in string: " << wcslen(str) << std::endl;
    
        for (const wchar_t* ch = str; *ch; ++ch) {
            std::cout << ((int)*ch) << std::endl;
        }
    }
    
    int main() {
        std::string input = u8"тлор";
        for (wchar_t ch : std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t>().from_bytes(input)) {
            std::wstring string_with_just_one_character(1, ch);
    
            test(string_with_just_one_character.c_str());
        }
        return 0;
    }