2012-03-07 3 views
0

C/C++ 프로그램에서 문자열/char를 \ uxxx 형식으로 변환하려고합니다. 지원 문자 'A'가 있습니다. \ u0041 (표준 유니 코드)로 변환하여 인쇄하고 싶습니다.C/C++에서 chararcter를 uxxx 형식으로 변환

두 번째로 유닉스 명령 유틸리티를 사용하여 (printf) \ uxxx 문자열을 char로 인쇄했습니다. "\ u092b"로 시도했는데 내 글꼴 파일과 다른 문자가 인쇄되었습니다. 어느 누구도이 이유를 설명 할 수 있습니까?

+0

당신이 그 일을하지 않았다 시도 했습니까? – geoffspear

+3

프로그램 내부의 문자를 나타내는 데 사용하는 내부 형식은 무엇입니까? ASCII/UTF-8/UTF-16/UTF-32/CP1490/ISO8859-1? \ u 형식은 4 자리 16 진수 또는 6 자리 숫자 만 지원합니까? 4 만 지원하는 경우 4 자리 16 진수로 모든 코드 포인트를 나타낼 수 있으므로 UTF-16으로 인코딩하고 긴 문자에 대용 암호 쌍을 사용해야합니다. –

답변

0

여기에는 표준 C++을 사용하는 함수가 있습니다 (CharT에 따라 일부 유효한 구현 정의 동작이 충족하지 못하는 요구 사항이있을 수 있음).

#include <codecvt> 
#include <sstream> 
#include <iomanip> 
#include <iostream> 

template<typename CharT,typename traits,typename allocator> 
std::basic_string<CharT,traits,allocator> 
to_uescapes(std::basic_string<CharT,traits,allocator> const &input) 
{ 
    // string converter from CharT to char. If CharT = char then no conversion is done. 
    // if CharT is char32_t or char16_t then the conversion is UTF-32/16 -> UTF-8. Not all implementations support this yet. 
    // if CharT is something else then this uses implementation defined encodings and will only work for us if the implementation uses UTF-8 as the narrow char encoding 
    std::wstring_convert<std::codecvt<CharT,char,std::mbstate_t>,CharT> convertA; 

    // string converter from UTF-8 -> UTF-32. Not all implementations support this yet 
    std::wstring_convert<std::codecvt<char32_t,char,std::mbstate_t>,char32_t> convertB; 

    // convert from input encoding to UTF-32 (Assuming convertA produces UTF-8 string) 
    std::u32string u32input = convertB.from_bytes(convertA.to_bytes(input)); 

    std::basic_stringstream<CharT,traits,allocator> ss; 
    ss.fill('0'); 
    ss << std::hex; 
    for(char32_t c : u32input) { 
     if(c < U'\U00010000') 
      ss << convertA.from_bytes("\\u") << std::setw(4) << (unsigned int)c; 
     else 
      ss << convertA.from_bytes("\\U") << std::setw(8) << (unsigned int)c; 
    } 
    return ss.str(); 
} 

template<typename CharT> 
std::basic_string<CharT> 
to_uescapes(CharT const *input) 
{ 
    return to_uescapes(std::basic_string<CharT>(input)); 
} 

int main() { 
    std::string s = to_uescapes(u8"Hello \U00010000"); 
    std::cout << s << '\n'; 
} 

이 인쇄해야합니다 :

\ u0048 \ u0065 \ u006c \ u006c \ u006f \ u0020 \ U00010000

+0

우분투에서 codecvt 헤더 파일이 없으므로 컴파일 할 수 없습니다. –