2014-12-31 12 views
11

Please help me come posso convertire wchar_t * var in string varStr nella console win32. Grazie in anticipoConversione di wchar_t * nella stringa

+0

http://stackoverflow.com/questions/4339960/how-do-i-convert-wchar-t-to-stdstring –

+0

mostra il codice, per favore (le API Win32) funzioni – grisha

risposta

35

Usa wstring, vedere questo codice:

// Your wchar_t* 
wchar_t* txt = L"Hello World"; 
wstring ws(txt); 
// your new String 
string str(ws.begin(), ws.end()); 
// Show String 
cout << str << endl; 
+0

Completamente sbagliato. Questo fallisce se 'txt' contiene caratteri non ascii. Se sostituisci '" Hello World "' con '" ... "', quindi '...' diventa '&'. Questa * soluzione * è altamente dannosa, causando la perdita di dati. – Benio

4

si dovrebbe utilizzare la classe wstring appartenente al namespace std. Ha un costruttore che accetta un parametro del tipo wchar_t *.

Ecco un esempio completo di utilizzo di questa classe.

wchar_t* characters=L"Test"; 
std::wstring string(characters); 

Non è necessario usare un costruttore contenente String.begin() e String.end() poiché il costruttore di std :: wstring assegna automaticamente memoria per memorizzare la matrice di wchar_t e copia la matrice al memoria allocata.

+0

Potrebbe il downvoter spiegare il suo downvote? –

Problemi correlati