Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

C/C++ - 리눅스 환경에서 u16string 문자열을 출력하는 방법

우선, u16string은 직접적으로 cout에 출력 지원이 안 됩니다.

std::u16string text = u"test";
cout << text << endl;

위와 같이 하면 이런 식으로 컴파일 오류가 발생합니다.

message : cannot convert ‘text’ (type ‘std::u16string’ {aka ‘std::__cxx11::basic_string<char16_t>’}) to type ‘const unsigned char*’

보통, 이런 경우 c_str() 함수의 결과를 출력하는데, u16string 계열은 이것마저도 단순히 해당 문자열의 주솟값을 출력할 뿐입니다.

cout << text.c_str() << endl; // 출력 결과: 0x7fffffffe330

답답하군요. ^^ 그럼, 어차피 16비트니까 wchar_t로 형변환하면 되지 않을까요? 그런데 실제로 해보면 정상적인 출력이 안 나옵니다.

const wchar_t* result = (wchar_t*)text.c_str();
wcout << result << endl; // 출력 결과: ts U  U

text의 메모리 표현이 "74 00 65 00 73 00 74 00 00"으로 나오는데, 왜 wchar_t로 정상적으로 받을 수 없는 걸까요? 그것은 리눅스에서 wchar_t 타입이 윈도우처럼 2바이트가 아닌 4바이트이기 때문입니다. 그로 인해 "74 00 65 00"이 한 글자를 표현하게 되고 결국 4바이트 유니코드에 해당하는 문자를 나타내 의도치 않은 결과가 나옵니다.

그래서 검색해 보면, u16string을 utf8로 변환 후 출력하라는 글들이 나옵니다.

how to print u32string and u16string to the console in c++
; https://stackoverflow.com/questions/45874857/how-to-print-u32string-and-u16string-to-the-console-in-c

std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
std::cout << converter.to_bytes(text) << std::endl; // 출력 결과: test




한 가지 유의할 사항은, converter.to_bytes 함수가 변환할 수 없는 문자를 포함하고 있으면 std::range_error 예외를 발생한다는 점입니다. 대개의 경우 정상적으로 초기화하지 않은 버퍼가 입력으로 들어간 경우에 발생할 텐데요, 이 외에도 Surrogate Pair를 지원하지 않아,

유니코드의 Surrogate Pair, Supplementary Characters가 뭘까요?
; https://www.sysnet.pe.kr/2/0/1710

정상적인 UTF-16 인코딩 문자열이라도 예외가 발생할 수 있음에 주의해야 합니다.

std::u16string text = u"\xd800\xdc00"; // U+10000에 대한 Surrogate Pair

std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
std::cout << converter.to_bytes(text) << std::endl; // 예외 발생

/*
terminate called after throwing an instance of 'std::range_error'
  what():  wstring_convert::to_bytes
*/

그래서, 가능한 try/catch로 to_bytes를 보호하는 것이 좋습니다.

try 
{
    std::u16string text = u"\xd800\xdc00";

    std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> converter;
    std::cout << converter.to_bytes(text) << std::endl; // 예외 발생
}
catch (std::range_error& e) {
    // 예외 처리
}

사실 이에 대해서는 문서에 명시돼 있긴 합니다.

codecvt_utf8
; https://learn.microsoft.com/en-us/cpp/standard-library/codecvt-utf8-class

Represents a locale facet that converts between wide characters encoded as UCS-2 or UCS-4, and a byte stream encoded as UTF-8.


보는 바와 같이 UTF-16이 아닌 UCS-2를 지원할 뿐입니다. 그런데, u16string의 value_type이 char16_t이고, char16_t가 UTF-16 인코딩을 받는 것을 보면,

char16_t
; https://en.cppreference.com/w/c/string/multibyte/char16_t

뭔가 잘 안 맞는 부분이 있는 듯합니다. 단지, UCS-4는 지원하기 때문에 다음과 같이 변환할 수는 있습니다.

// How to decode surrogate characters encoded as UTF8?
// ; https://stackoverflow.com/questions/38293373/how-to-decode-surrogate-characters-encoded-as-utf8

const wchar_t* text = L"\U00010000";
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

std::string utf8str = converter.to_bytes(text); // F0 90 80 80

결국 surrogate-pair에 해당하는 d800, dc00 바이트 스트림을 utf-8로 변환하는 방법은...? 직접 그에 대한 처리를 해야 합니다. (잘 찾아보면 누군가 만들어 둔 것이 있을지도... ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/11/2022]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2022-10-12 10시24분
[이승준] 더큰 문제가 있습니다.
codecvt api들이 C++17에서 deprecated 되었다가 C++20에서 돌아왔다는 겁니다.
사용하신 codecvt_utf8 api는 여전히 삭제 상태고요.
https://stackoverflow.com/questions/42946335/deprecated-header-codecvt-replacement
Windows에서는 WideCharToMultiByte 요런걸로 처리가 되는데.
리눅스는 C++11 또는 C++20을 써야 할겁니다.

하~ 회사에서 사용하는 비주얼 스튜디오가 2015랑 2017만 이써어서 C++20에서 돌아온건 저도 몰랐네요.
[guest]
2022-10-12 11시14분
좋은 정보 감사드립니다. ^^ 그래도 c++20에서 돌아왔다니 다행이군요.
정성태

[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13599정성태4/17/2024245닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024260닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024330닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024623닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024749닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024963닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241030닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241201C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241162닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241138닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241147오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241289Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241092Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241148Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241221Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241135닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241626닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241864닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241676닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...