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에서 돌아왔다니 다행이군요.
정성태

... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13180정성태12/2/20224943.NET Framework: 2074. C# - 스택 메모리에 대한 여유 공간 확인하는 방법파일 다운로드1
13179정성태12/2/20224365Windows: 216. Windows 11 - 22H2 업데이트 이후 Terminal 대신 cmd 창이 뜨는 경우
13178정성태12/1/20224866Windows: 215. Win32 API 금지된 함수 - IsBadXxxPtr 유의 함수들이 안전하지 않은 이유파일 다운로드1
13177정성태11/30/20225597오류 유형: 829. uwsgi 설치 시 fatal error: Python.h: No such file or directory
13176정성태11/29/20224517오류 유형: 828. gunicorn - ModuleNotFoundError: No module named 'flask'
13175정성태11/29/20226144오류 유형: 827. Python - ImportError: cannot import name 'html5lib' from 'pip._vendor'
13174정성태11/28/20224710.NET Framework: 2073. C# - VMMap처럼 스택 메모리의 reserve/guard/commit 상태 출력파일 다운로드1
13173정성태11/27/20225398.NET Framework: 2072. 닷넷 응용 프로그램의 스레드 스택 크기 변경
13172정성태11/25/20225207.NET Framework: 2071. 닷넷에서 ESP/RSP 레지스터 값을 구하는 방법파일 다운로드1
13171정성태11/25/20224822Windows: 214. 윈도우 - 스레드 스택의 "red zone"
13170정성태11/24/20225134Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225714Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20224998제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20225036.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224763개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224668개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225569개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225519개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226587.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225804.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225753.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228974.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225231오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225900.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226803.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226303디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...