使用wchar_t改变char的类型不像L那样

问题描述 投票:0回答:1

在我的代码中,我试图创建大量的4个字符,其中每个字符都包含一个西里尔字母。

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

一切正常,我预计输出。它只是测试,实际上我需要将元素从字符串转换为相同的类型,如OUT_STRING;我试着用这样的东西:

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

但它不起作用,在输出中我有一个矩形。

c++ types wchar-t
1个回答
0
投票

我想你想用UTF-8编码中的std :: string传入一个字符串并一次处理一个字符,每次将单个字符转换为长度为1的宽字符串,这样就可以将它传递给TTF_SizeUNICODETTF_RenderUNICODE_Blended

我将演示相关的字符串转换代码。

这是一个test函数,它需要一个以null结尾的宽字符串,其中只包含一个字符。 main的正文显示了如何将UTF-8字符串转换为UTF-16(使用codecvt_utf8_utf16)以及如何将单个字符转换为字符串(使用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;
}
© www.soinside.com 2019 - 2024. All rights reserved.