[英]In C, how to print UTF-8 char if given its bytes in char variables?
如果我將 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 %s\n", 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: %s\n", mbS);
int requiredSize = mbstowcs(NULL, mbS, 0);
printf("Output size including null terminator is %d\n\n", 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: %ls\n", len, wideOutput );
}
return 0;
}
Output:
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);
這取決於您的終端或您用來顯示output 的任何設備,以正確理解和呈現 UTF-8 編碼。 這與您的程序使用的編碼無關,也與寬字符無關。
同樣對於 3 和 4 字節 UTF-8 字符?
你會 output 他們。
如果您的終端或您發送字節的設備不理解 UTF-8 編碼,那么您必須將字節轉換為設備可以理解的內容。 通常,您會為此使用外部庫,例如iconv
。 或者,您可以setlocale("C.utf-8")
然后將您的字節轉換為wchar_t
,然后setlocale("C.your_target_encoding")
然后將字節轉換為該編碼或 output 字節與%ls
。 所有%ls
所做的(在普通系統上)是它將字符串轉換回多字節然后輸出它。 wide stream輸出到終端也是一樣,先轉換,再輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.