使用 wchar_t 更改字符类型不像 L
Changing type of char using wchar_t used not so like L
在我的代码中,我尝试创建大量的 4 位字符,其中每个字符都包含一个西里尔字母。
wchar_t OUT_STRING[4] = { L'т',L'л',L'о',L'р' };
一切正常,我有预期的输出。这只是测试,实际上我需要将元素从字符串转换为与 OUT_STRING 中相同的类型;我试着用这样的东西:
wchar_t OUT_STRING[4] = { (wchar_t)'т',L'л',L'о',L'р' };
但它没有用,在输出中我有一个矩形。
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;
}
在我的代码中,我尝试创建大量的 4 位字符,其中每个字符都包含一个西里尔字母。
wchar_t OUT_STRING[4] = { L'т',L'л',L'о',L'р' };
一切正常,我有预期的输出。这只是测试,实际上我需要将元素从字符串转换为与 OUT_STRING 中相同的类型;我试着用这样的东西:
wchar_t OUT_STRING[4] = { (wchar_t)'т',L'л',L'о',L'р' };
但它没有用,在输出中我有一个矩形。
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;
}