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)
13532정성태1/17/20242179닷넷: 2205. C# - SuperSimpleTcp 사용 시 주의할 점파일 다운로드1
13531정성태1/16/20242067닷넷: 2204. C# - TCP KeepAlive에 새로 추가된 Retry 옵션파일 다운로드1
13530정성태1/15/20242043닷넷: 2203. C# - Python과의 AES 암호화 연동파일 다운로드1
13529정성태1/15/20241922닷넷: 2202. C# - PublishAot의 glibc에 대한 정적 링킹하는 방법
13528정성태1/14/20242062Linux: 68. busybox 컨테이너에서 실행 가능한 C++, Go 프로그램 빌드
13527정성태1/14/20242012오류 유형: 892. Visual Studio - Failed to launch debug adapter. Additional information may be available in the output window.
13526정성태1/14/20242109닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242065오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242117오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241933오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242094닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242154닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241892오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241985닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242255닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242101스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242194닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242473닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242116개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242038닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20242002개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20242021닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241956닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241980오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242029오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242718닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...