C C 的編碼轉換

2021-08-07 23:04:14 字數 990 閱讀 7605

本來以為轉碼只能用第三方庫或者api的,沒想到標準庫也帶了轉碼的函式

用到wcstombs、mbstowcs,編碼要用setlocale設定,不過crt增強版的_wcstombs_l和_mbstowcs_l可以設定區域性的locale

#include 

#include

char* w2a(wchar_t* src)

wchar_t* a2w(char* src)

用到c++11的wstring_convert的to_bytes和from_bytes,編碼還是看locale

#include 

#include

std:

:string

w2a(const std:

:wstring& src)

std:

:wstring

a2w(const std:

:string& src)

順帶一提如果要改變輸出流的編碼只需要呼叫imbue,還有codecvt標頭檔案自帶了各種unicode編碼轉utf-8的codecvt

#include 

#include

// ...

std::wofstream f(l"這是utf-8檔案.txt");

f.imbue(std::locale(std::locale(), new std::codecvt_utf8_utf16));

f << l"這是utf-16"

<< std::endl;

這個知道的人就多了,用到widechartomultibyte和multibytetowidechar,可以設定**頁

#include 

char* w2a(wchar_t* src)

wchar_t* a2w(char* src)

C C 字元編碼的轉換 ut8 gb2312

這是個類strcoding strcoding.h檔案 pragma once include include include using namespace std class strcoding 這是個類strcoding strcoding.cpp檔案 include stdafx.h inc...

C C 字元編碼的轉換 ut8 gb2312

有三分 strcoding.h strcoding.cpp test.cpp cpp view plain copy print?這是個類strcoding strcoding.件 pragma once include include include using namespace std cla...

一套Windows上C C 的編碼轉換函式

所以把常用的轉換封裝一下,用c的語法實現。支援c c 注意這些函式都會在堆中建立並返回新的字串,所以返回的字串在使用完以後要顯示銷毀使用free 否則會造成記憶體洩漏。第一條巨集是取消煩人的vs編譯器強制要求使用 s函式的巨集。如果在非vs編譯器下會被自動忽略。define crt secure n...