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)
13577정성태3/9/20241876닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241545닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
13575정성태3/7/20241678닷넷: 2227. 최신 C# 문법을 .NET Framework 프로젝트에 쓸 수 있을까요?
13574정성태3/6/20241558닷넷: 2226. C# - "Docker Desktop for Windows" Container 환경에서의 IPv6 DualMode 소켓
13573정성태3/5/20241564닷넷: 2225. Windbg - dumasync로 분석하는 async/await 호출
13572정성태3/4/20241644닷넷: 2224. C# - WPF의 Dispatcher Queue로 알아보는 await 호출의 hang 현상파일 다운로드1
13571정성태3/1/20241624닷넷: 2223. C# - await 호출과 WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13570정성태2/29/20241636닷넷: 2222. C# - WPF의 Dispatcher Queue 동작 확인파일 다운로드1
13569정성태2/28/20241546닷넷: 2221. C# - LoadContext, LoadFromContext 그리고 GAC파일 다운로드1
13568정성태2/27/20241608닷넷: 2220. C# - .NET Framework 프로세스의 LoaderOptimization 설정을 확인하는 방법파일 다운로드1
13567정성태2/27/20241618오류 유형: 898. .NET Framework 3.5 이하에서 mscoree.tlb 참조 시 System.BadImageFormatException파일 다운로드1
13566정성태2/27/20241632오류 유형: 897. Windows 7 SDK 설치 시 ".NET Development" 옵션이 비활성으로 선택이 안 되는 경우
13565정성태2/23/20241479닷넷: 2219. .NET CLR2 보안 모델에서의 개별 System.Security.Permissions 제어
13564정성태2/22/20241614Windows: 259. Hyper-V Generation 1 유형의 VM을 Generation 2 유형으로 바꾸는 방법
13563정성태2/21/20241646디버깅 기술: 196. windbg - async/await 비동기인 경우 메모리 덤프 분석의 어려움
13562정성태2/21/20241646오류 유형: 896. ASP.NET - .NET Framework 기본 예제에서 System.Web에 대한 System.IO.FileNotFoundException 예외 발생
13561정성태2/20/20241745닷넷: 2218. C# - (예를 들어, Socket) 비동기 I/O에 대한 await 호출 시 CancellationToken을 이용한 취소파일 다운로드1
13560정성태2/19/20241747디버깅 기술: 195. windbg 분석 사례 - Semaphore 잠금으로 인한 Hang 현상 (닷넷)
13559정성태2/19/20242626오류 유형: 895. ASP.NET - System.Security.SecurityException: 'Requested registry access is not allowed.'
13558정성태2/18/20241821닷넷: 2217. C# - 최댓값이 1인 SemaphoreSlim 보다 Mutex 또는 lock(obj)를 선택하는 것이 나은 이유
13557정성태2/18/20241621Windows: 258. Task Scheduler의 Author 속성 값을 변경하는 방법
13556정성태2/17/20241684Windows: 257. Windows - Symbolic (hard/soft) Link 및 Junction 차이점
13555정성태2/15/20241956닷넷: 2216. C# - SemaphoreSlim 사용 시 주의점
13554정성태2/15/20241709VS.NET IDE: 189. Visual Studio - 닷넷 소스코드 디컴파일 찾기가 안 될 때
13553정성태2/14/20241736닷넷: 2215. windbg - thin/fat lock 없이 동작하는 Monitor.Wait + Pulse
13552정성태2/13/20241695닷넷: 2214. windbg - Monitor.Enter의 thin lock과 fat lock
1  [2]  3  4  5  6  7  8  9  10  11  12  13  14  15  ...