Skip to content

Instantly share code, notes, and snippets.

@alexeyr
Created June 29, 2021 16:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexeyr/c59ea2161bab919cf7dd7ddf2012cddc to your computer and use it in GitHub Desktop.
Save alexeyr/c59ea2161bab919cf7dd7ddf2012cddc to your computer and use it in GitHub Desktop.
The proper way to use wcsrtombs to convert a const wchar_t* to an std::string (so far as I can tell)
#include <cstring>
#include <cwchar>
inline void ResetMbState(std::mbstate_t &state) {
// this is really the recommended way to zero-initialize an mbstate_t
std::memset(&state, 0, sizeof(std::mbstate_t));
}
inline std::string WCharPtrToString(const wchar_t *data) {
std::mbstate_t state;
ResetMbState(state);
const wchar_t *src = data;
size_t length = std::wcsrtombs(nullptr, &src, 0, &state);
// replace by `if` if you want to actually do something on error
ASSERT(length != static_cast<size_t>(-1));
std::string result(length + 1, '\0);
ResetMbState(state);
src = data;
std::wcsrtombs(&result[0], &src, length + 1, &state);
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment