2008-08-26 5 views

답변

96

MSDN 기사에 대한 링크를 제공해 주셔서 감사합니다. 이것은 내가 찾고 있었던 바로 그 것이다.

std::wstring s2ws(const std::string& s) 
{ 
    int len; 
    int slength = (int)s.length() + 1; 
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len]; 
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); 
    std::wstring r(buf); 
    delete[] buf; 
    return r; 
} 

std::wstring stemp = s2ws(myString); 
LPCWSTR result = stemp.c_str(); 
+3

(이 질문을 무작위로 찾았습니다. C++ 이후로 오랜 시간이 걸렸습니다.) 그래서 표준 라이브러리에는 std :: string -> std :: wstring 변환이 없습니까? 이상하게 보입니다. 좋은 이유가 있니? – Domenic

+4

std :: vector 을 사용하여 buf에 대한 저장소를 생성하면 예외가 발생하면 임시 버퍼가 해제됩니다. –

+51

이유 # 233에 대한 이유는 C++ 단순한 문자열 변환을위한 나 ... 10 행 코드 =/ –

2

을 LPCWSTR하기 위해, 당신은 std :: wstring을 사용할 수 있습니다.

편집 : 죄송합니다. 설명이 필요하지 않지만 실행해야합니다.

를 사용하여 표준 : : wstring의 :: c_str() 당신은 ATL/MFC 환경에있는 경우

+6

* Q : "X에서 Y로 변환해야합니다."* - * A : "X 대신 A를 사용하는 직업을 찾으십시오."* 이것은 쓸모가 없습니다. – IInspectable

7

, 당신은 ATL 변환 매크로를 사용할 수 있습니다

#include <atlbase.h> 
#include <atlconv.h> 

. . . 

string myStr("My string"); 
CA2W unicodeStr(myStr); 

당신은 다음과 같이 unicodeStr을 사용할 수 있습니다 LPCWSTR. 유니 코드 문자열에 대한 메모리가 스택에 만들어지고 unicodeStr에 대한 소멸자가 실행되면서 해제됩니다.

88

이 솔루션은 실제로 다른 제안들보다 훨씬 더 쉽다 :

모두의
std::wstring stemp = std::wstring(s.begin(), s.end()); 
LPCWSTR sw = stemp.c_str(); 

, 그것은 플랫폼에 독립적입니다. H2H :

+2

죄송합니다 Benny하지만 그건 나를 위해 작동하지 않습니다, Toran의 자신의 솔루션을 잘 작동하는 것 (하지만 ...!)! –

+0

Working Fine. 감사. – Durgesh

+24

이것은 모든 문자가 1 바이트 즉, ASCII 또는 [ISO-8859-1] (http : //en.wikipedia.org/wiki/ISO-8859-1). 멀티 바이트는 UTF-8을 포함하여 비참하게 실패 할 것입니다. –

-2
string s = "Hello World"; 
std::wstring stemp = std::wstring(s.begin(), s.end()); 
LPCWSTR title =(LPCWSTR) stemp.c_str(); 

LPCWSTR wname =(LPCWSTR) "Window"; 


HINSTANCE hInst = GetModuleHandle(0); 
WNDCLASS cls = { CS_HREDRAW|CS_VREDRAW, WndProc, 0, 0, hInst, LoadIcon(hInst,MAKEINTRESOURCE(IDI_APPLICATION)), 
    LoadCursor(hInst,MAKEINTRESOURCE(IDC_ARROW)), GetSysColorBrush(COLOR_WINDOW),0,wname }; 
RegisterClass(&cls); 
HWND window = CreateWindow(wname,title,WS_OVERLAPPEDWINDOW|WS_VISIBLE,64,64,640,480,0,0,hInst,0); 

MSG Msg; 
while(GetMessage(&Msg,0,0,0)) 
{ 
    TranslateMessage(&Msg); 
    DispatchMessage(&Msg); 
} 
return Msg.wParam; 
0

당신은 중간으로 CString를 사용할 수 있습니다

std::string example = "example"; 
CString cStrText = example.c_str(); 
LPTSTR exampleText = cStrText.GetBuffer(0); 
관련 문제