2013-08-27 119 views
-1

我想將TCHAR nameBuf[]轉換爲stringTCHAR []轉換爲字符串

TCHAR nameBuf[MAX_COMPUTERNAME_LENGTH + 2]; 

DWORD nameBufSize; 

nameBufSize = sizeof nameBuf - 1; 

GetComputerName(nameBuf, &nameBufSize); //store computer name into nameBuf 

_tprintf(_T("%s"), nameBuf); //print the computer name 
+3

*您可以*使用'的std :: basic_string ',但爲什麼不在第一個地方使用寬字符呢? – chris

+0

這裏的T總是意味着寬嗎? – doctorlove

+1

_T只有在_UNICODE_被定義時纔會變寬。 –

回答

0

讓我們把類型弄清楚。請參見下面修改後的代碼:

WCHAR nameBuf[MAX_COMPUTERNAME_LENGTH + 2]; 

DWORD nameBufSize; 

nameBufSize = sizeof nameBuf - 1; 

GetComputerNameW(nameBuf, &nameBufSize); //store computer name into nameBuf 

wprintf_s(L"%s", nameBuf); //print the computer name 
+0

那麼如何讓'string NAME = nameBuf'? –

+0

'nameBufSize = sizeof nameBuf - 1';應該是'nameBufSize = MAX_COMPUTERNAME_LENGTH + 1'。因爲大小應該是字符而不是字節。 – john

+0

@Xynus如果你需要使用字符串而不是wstring,那麼使用「A」等價物而不是「W」。 – Vivek

0

如果你想使用窄字符(好像你這樣做),那麼這段代碼

char nameBuf[MAX_COMPUTERNAME_LENGTH + 2]; 
DWORD nameBufSize; 
nameBufSize = sizeof nameBuf - 1; 
GetComputerNameA(nameBuf, &nameBufSize); //store computer name into nameBuf 
printf_s("%s", nameBuf); //print the computer name 
string NAME = nameBuf; 

未經測試的代碼