Panel użytkownika
Nazwa użytkownika:
Hasło:
Nie masz jeszcze konta?

konwersja string na wstring

Ostatnio zmodyfikowano 2024-06-05 22:06
Autor Wiadomość
tBane
Temat założony przez niniejszego użytkownika
» 2024-06-05 21:25:08
Nie wiem czy o to chodziło ale ..

ten tekst bezpo?rednio trafia do SFML:
87 105 116 97 109 32 119 32 103 114 122 101 32 79 110 101 32 45 32 84 104 101 32 66 101 103 105 110 110 105 110 103 46 32 90 97 380 243 322 263
71 281 347 108 261 32 74 97 378 324 46 0
P-181214
pekfos
» 2024-06-05 21:43:40
Tego zera nie powinno tam być. To jest błąd w ConvertUtf8ToWide().
C/C++
std::wstring wideStr( wideCharCount, 0 );
MultiByteToWideChar( CP_UTF8, 0, utf8Str.c_str(), - 1, & wideStr[ 0 ], wideCharCount );
wideStr.pop_back(); // usuń zero dodane przez MultiByteToWideChar
return wideStr;
P-181216
tBane
Temat założony przez niniejszego użytkownika
» 2024-06-05 21:47:26
Dzięki Mistrzu! :-)
Jednak nie takie piekło
P-181217
pekfos
» 2024-06-05 21:55:00
Jak w końcu odpowiesz na pytanie, to może i tak.

Dokładnie to się bierze stąd:
MultiByteToWideChar does not null-terminate an output string if the input string length is explicitly specified without a terminating null character. To null-terminate an output string for this function, the application should pass in -1 or explicitly count the terminating null character for the input string.
https://learn.microsoft.com/en-us/windows/win32/api/stringapiset/nf-stringapiset-multibytetowidechar#return-value
Wiec jako że długość napisu wejściowego jest znana, można to zrobić optymalniej podając ją do MultiByteToWideChar().
C/C++
int wideCharCount = MultiByteToWideChar( CP_UTF8, 0, utf8Str.c_str(), utf8Str.size(), nullptr, 0 );
if( wideCharCount == 0 ) {
   
throw std::runtime_error( "Error in MultiByteToWideChar" );
}

std::wstring wideStr( wideCharCount, 0 );
MultiByteToWideChar( CP_UTF8, 0, utf8Str.c_str(), utf8Str.size(), & wideStr[ 0 ], wideCharCount );
return wideStr;
Oszczędza 2 strleny i alokowanie dodatkowego znaku na zero które i tak chcemy usunąć.
P-181218
tBane
Temat założony przez niniejszego użytkownika
» 2024-06-05 22:06:25
Ogólnie to muszę się przespać z tym kodem. Dziś już nie jestem w stanie niczego zrozumieć.
ja miałem coś takiego:

C/C++
std::wstring ConvertUtf8ToWide( const std::string & utf8Str ) {
   
// Convert string (UTF-8) to wstring (wide string)
   
if( utf8Str.empty() ) {
       
return std::wstring();
   
}
   
   
int wideCharCount = MultiByteToWideChar( CP_UTF8, 0, utf8Str.c_str(), - 1, nullptr, 0 );
   
if( wideCharCount == 0 ) {
       
throw std::runtime_error( "Error in MultiByteToWideChar" );
   
}
   
   
std::wstring wideStr( wideCharCount, 0 );
   
MultiByteToWideChar( CP_UTF8, 0, utf8Str.c_str(), - 1, & wideStr[ 0 ], wideCharCount );
   
return wideStr;
}
P-181219
1 2 3 « 4 »
Poprzednia strona Strona 4 z 4