2016-12-19 45 views
3

我在WINAPI一個初學者,我想轉換wstringstream到LPCWSTR這樣的(內部WM_PAINT):轉換wstringstream到LPCWSTR

wstringstream ws; 
ws << "my text" << endl; 
LPCWSTR myWindowOutput = ws.str().c_str(); 
hdc = BeginPaint(hWnd, &ps); 
TextOut(hdc, 150, 305, myWindowOutput, 10); 

只產生垃圾雖然,有人可以幫忙嗎?謝謝。

+0

你如何顯示字符串? –

回答

5

LPCWSTR myWindowOutput = ws.str().c_str()會產生一個臨時的(str()調用的返回值),只要完整的語句結束就會消失。由於需要臨時,你需要把它向下移動的號召,最終消耗它:

TextOutW(hdc, 150, 305, ws.str().c_str(), static_cast<int>(ws.str().length())); 

同樣,臨時生活直到全部語句結束。這一次,這足以讓API調用使用它。

作爲替代方案,你可以的str()返回值綁定到常量參考1),並使用它。這可能是比較合適的,因爲你需要使用返回值的兩倍(獲取一個指針到緩衝區,並確定其大小):

wstringstream ws; 
ws << "my text" << endl; 
hdc = BeginPaint(hWnd, &ps); 
const wstring& s = ws.str(); 
TextOutW(hdc, 150, 305, s.c_str(), static_cast<int>(s.length())); 


1) 爲什麼這個工程是解釋在GotW #88: A Candidate For the 「Most Important const」之下。