在C中,如果在字符变量中给定UTF-8字符的字节,如何打印UTF-8字符



如果我有c1,c2作为char变量(这样c1c2将是UTF-8字符的字节序列(,我如何创建和打印UTF-8字符?

对于3字节和4字节的UTF-8字符类似吗?

我一直在尝试使用mbstowcs()的各种方法,但就是无法使其发挥作用。

我设法写了一个工作示例
c1'xce'c2'xb8'时,结果为θ
事实证明,在使用mbstowcs之前,我必须先调用setlocale

#include <stdlib.h>
#include <stdio.h>
#include <locale.h>

int main()
{
char* localeInfo = setlocale(LC_ALL, "en_US.utf8");
printf("Locale information set to %sn", localeInfo);

const char c1 = 'xce';
const char c2 = 'xb8';
int byteCount = 2;
char* mbS = (char*) malloc(byteCount + 1);
mbS[0] = c1; 
mbS[1] = c2; 
mbS[byteCount] = 0; //null terminator
printf("Directly using printf: %sn", mbS);


int requiredSize = mbstowcs(NULL, mbS, 0); 
printf("Output size including null terminator is %dnn", requiredSize +1);

wchar_t *wideOutput = (wchar_t *)malloc( (requiredSize +1) * sizeof( wchar_t ));

int len = mbstowcs(wideOutput , mbS, requiredSize +1 ); 
if(len == -1){
printf("Failed conversion!");
}else{
printf("Converted %d character(s). Result: %lsn", len, wideOutput );
}
return 0;

}

输出:

Locale information set to en_US.utf8
Directly using printf: θ
Output size including null terminator is 2
Converted 1 character(s). Result: θ

对于3或4字节的utf8字符,可以使用类似的方法。

如果我有c1,c2作为char变量(这样c1c2将是UTF-8字符的字节序列(,我如何创建和打印UTF-8字符?

它们已经是一个UTF-8字符了。你只需要把它们打印出来。

putchar(c1);
putchar(c2);

这取决于您的终端或您用于显示输出的任何设备,以正确理解和呈现UTF-8编码。这与程序使用的编码无关,也与宽字符无关。

对于3字节和4字节的UTF-8字符类似吗?

您将输出它们。


如果您的终端或发送字节的设备不理解UTF-8编码,则必须将字节转换为设备能够理解的内容。通常,您会使用外部库,如iconv。或者,您可以setlocale("C.utf-8")然后将您的字节转换为wchar_t,然后setlocale("C.your_target_encoding"),然后将字节转换为该编码,或者使用%ls输出字节。%ls(在普通系统上(所做的就是将字符串转换回多字节,然后输出。输出到终端的宽流也会这样做,先转换,然后输出。

最新更新