File tree Expand file tree Collapse file tree 1 file changed +13
-5
lines changed
Expand file tree Collapse file tree 1 file changed +13
-5
lines changed Original file line number Diff line number Diff line change @@ -114,11 +114,19 @@ namespace dlib
114114
115115 const std::string convert_wstring_to_mbstring (const std::wstring &src)
116116 {
117- using namespace std ;
118- std::string str;
119- str.resize ((src.length () + 1 ) * MB_CUR_MAX);
120- wcstombs (&str[0 ], src.c_str (), str.size ());
121- return std::string (&str[0 ]);
117+ std::mbstate_t st{};
118+ const wchar_t * p = src.c_str ();
119+
120+ // Compute length
121+ size_t n = std::wcsrtombs (nullptr , &p, 0 , &st);
122+ if (n == static_cast <std::size_t >(-1 )) throw std::runtime_error (" Invalid wide sequence / locale mismatch" );
123+
124+ // Convert
125+ std::string out (n, ' \0 ' );
126+ st = std::mbstate_t {};
127+ n = std::wcsrtombs (out.data (), &p, out.size (), &st);
128+ if (n == static_cast <std::size_t >(-1 )) throw std::runtime_error (" Conversion failed" );
129+ return out;
122130 }
123131
124132// ----------------------------------------------------------------------------------------
You can’t perform that action at this time.
0 commit comments