Convert Between char* string to wchar_t* string

code snippet ( char* string to wchar_t* string )

inline std::unique_ptr<wchar_t[]> to_wchar_ts(const char * orig)
{
    // newsize describes the length of the   
    // wchar_t string called wcstring in terms of the number   
    // of wide characters, not the number of bytes.  
    size_t newsize = strlen(orig) + 1;

    // The following creates a buffer large enough to contain   
    // the exact number of characters in the original string  
    // in the new format. If you want to add more characters  
    // to the end of the string, increase the value of newsize  
    // to increase the size of the buffer.  
    std::unique_ptr<wchar_t[]> wcstring(new wchar_t[newsize]);

    // Convert char* string to a wchar_t* string.  
    size_t convertedChars = 0;
    mbstowcs_s(&convertedChars, wcstring.get(), newsize, orig, _TRUNCATE);
    return wcstring;
}


code snippet (  wchar_t* string to char* string )

inline std::unique_ptr<char[]> to_chars(wchar_t *orig)
{
    // Convert the wchar_t string to a char* string. Record   
    // the length of the original string and add 1 to it to  
    // account for the terminating null character.  
    size_t origsize = wcslen(orig) + 1;

    // Allocate two bytes in the multibyte output string for every wide  
    // character in the input string (including a wide character  
    // null). Because a multibyte character can be one or two bytes,  
    // you should allot two bytes for each character. Having extra  
    // space for the new string is not an error, but having  
    // insufficient space is a potential security problem.  
    const size_t newsize = origsize * 2;

    // The new string will contain a converted copy of the original  
    // string.  
    std::unique_ptr<char[]> nstring(new char[newsize]);

    // Put a copy of the converted string into nstring  
    size_t convertedChars = 0;
    wcstombs_s(&convertedChars, nstring.get(), newsize, orig, _TRUNCATE);
    return nstring;
}

From :How to: Convert Between Various String Types


But, it won't work for Chinese/Japanese Characters because wcstombs_s will return  EILSEQ: Illegal sequence of bytes (for example, in an MBCS string).
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值