如何将const WCHAR *转换为const char *

时间:2012-09-28 09:58:37

标签: c++

CString output ;
const WCHAR* wc = L"Hellow World" ;
if( wc != NULL )
{   
     output.Append(wc);
}
printf( "output: %s\n",output.GetBuffer(0) );

6 个答案:

答案 0 :(得分:16)

你也可以试试这个:

#include <comdef.h>  // you will need this
const WCHAR* wc = L"Hello World" ;
_bstr_t b(wc);
const char* c = b;
printf("Output: %s\n", c);

_bstr_t实现了以下转换运算符,我觉得非常方便:

operator const wchar_t*( ) const throw( ); 
operator wchar_t*( ) const throw( ); 
operator const char*( ) const; 
operator char*( ) const;

编辑:关于答案评论的澄清:行const char* c = b;导致由_bstr_t实例创建和管理的字符串的窄字符副本,该实例将在销毁时释放一次。操作符只返回指向此副本的指针。因此,无需复制此字符串。此外,在问题中,CString::GetBuffer会返回LPTSTR(即TCHAR*)和 LPCTSTR(即const TCHAR*)。

另一个选择是使用转换宏:

USES_CONVERSION;
const WCHAR* wc = L"Hello World" ;
const char* c = W2A(wc);

这种方法的问题在于转换后的字符串的内存是在堆栈上分配的,因此字符串的长度是有限的。但是,这个转换宏系列允许您选择用于转换的代码页,如果宽字符串包含非ANSI字符,通常需要这样。

答案 1 :(得分:7)

您可以将sprintf用于此目的:

const char output[256];
const WCHAR* wc = L"Hellow World" ;
sprintf(output, "%ws", wc );

答案 2 :(得分:3)

我的Linux代码

// Debian GNU/Linux 8 "Jessie" (amd64)

#include <locale.h>
#include <stdlib.h>
#include <stdio.h>

// Use wcstombs(3) to convert Unicode-string (wchar_t *) to UTF-8 (char *)
// http://man7.org/linux/man-pages/man3/wcstombs.3.html

int f(const wchar_t *wcs) {
        setlocale(LC_ALL,"ru_RU.UTF-8");
        printf("Sizeof wchar_t: %d\n", sizeof(wchar_t));
        // on Windows, UTF-16 is internal Unicode encoding (UCS2 before WinXP)
        // on Linux, UCS4 is internal Unicode encoding
        for (int i = 0; wcs[i] > 0; i++) printf("%2d %08X\n",i,wcs[i]);
        char s[256];
        size_t len = wcstombs(s,wcs,sizeof(s));
        if (len > 0) {
                s[len] = '\0';
                printf("mbs: %s\n",s);
                for (int i = 0; i < len; i++)
                        printf("%2d %02X\n",i,(unsigned char)s[i]);
                printf("Size of mbs, in bytes: %d\n",len);
                return 0;
        }
        else return -1;
}

int main() {
        f(L"Привет"); // 6 symbols
        return 0;
}

如何构建

#!/bin/sh
NAME=`basename $0 .sh`
CC=/usr/bin/g++-4.9
INCS="-I."
LIBS="-L."
$CC ${NAME}.c -o _${NAME} $INCS $LIBS

输出

$ ./_test 
Sizeof wchar_t: 4
 0 0000041F
 1 00000440
 2 00000438
 3 00000432
 4 00000435
 5 00000442
mbs: Привет
 0 D0
 1 9F
 2 D1
 3 80
 4 D0
 5 B8
 6 D0
 7 B2
 8 D0
 9 B5
10 D1
11 82
Size of mbs, in bytes: 12

答案 3 :(得分:1)

你可以做到这一点,或者你可以做一些更清洁的事情:

std::wcout << L"output: " << output.GetString() << std::endl;

答案 4 :(得分:1)

这很简单,因为CString只是CStringT的typedef,您还可以访问CStringACStringW(您应该阅读有关差异的文档) )。

CStringW myString = L"Hello World";
CString myConvertedString = myString;

答案 5 :(得分:0)

您可以为此使用 sprintf,正如@l0pan 所提到的(但我使用了 %ls 而不是 %ws):

char output[256];
const WCHAR* wc = L"Hello World" ;
sprintf(output, "%ws", wc ); // did not work for me (Windows, C++ Builder)
sprintf(output, "%ls", wc ); // works