[RESOLVED] Da std::string a std::wstring e viceversa

di Anonimizzato7532 il
3 risposte
Ragazzi buonasera. Di solito nei miei progetti per la conversione da MBCS a UNICODE e viceversa uso queste funzioni:

std::wstring str_to_wstr(const std::string &str, UINT cp)
{
	int len = MultiByteToWideChar(cp, 0, str.c_str(), str.length(), 0, 0);
	if (!len)
		return L"";

	std::vector<wchar_t> wbuff(len + 1);
	if (!MultiByteToWideChar(cp, 0, str.c_str(), str.length(), &wbuff[0], len))
		return L"";

	return &wbuff[0];
}
e

std::string wstr_to_str(const std::wstring &wstr, UINT cp)
{
	int len = WideCharToMultiByte(cp, 0, wstr.c_str(), wstr.length(), 0, 0, 0, 0);
	if (!len)
		return "";

	std::vector<char> abuff(len + 1);

	if (!WideCharToMultiByte(cp, 0, wstr.c_str(), wstr.length(), &abuff[0], len, 0, 0))
	{
		return "";
	}

	return &abuff[0];
}
Mi stavo chiedendo: Conoscete qualche altro modo per fare queste trasformazioni magari anche cross-platform senza scomodare la CString?
Grazie.

3 Risposte

  • Hello skynet,

    Se non dico una castronata mattiniera dovrebbero essere definite in cstdlib:
    
    int mblen ( const char * pmb, size_t max );
    int mbtowc ( wchar_t * pwc, const char * pmb, size_t max );
    size_t mbstowcs ( wchar_t * wcstr, const char * mbstr, size_t max );
    int wctomb ( char * pmb, wchar_t character );
    size_t wcstombs ( char * mbstr, const wchar_t * wcstr, size_t max );
    
    Sempre che MBCS sia quello che penso...
  • Si, quelle sono le funzioni di libreria per trasformare da UNICODE a MBCS e viceversa. Però non tengono conto del Codepage del sistema operativo (ne potrebbero farlo, comunque).
    Se si deve tenere conto pure del Codepage, tocca usare le API del sistema operativo.
    Comunque lo sviluppo della funzione di trasformazione è più o meno lo stesso, quindi non c'è molta scelta.
  • Ok quindi mi tengo quelle che ho. Grazie cmq ragazzi, al prossimo dubbio
Devi accedere o registrarti per scrivere nel forum
3 risposte