I want to implement two functions, convert between string and wstring, the program runs in linux centos7 gcc version 4.8.5
below is my implementation, if you remove setlocale (LC_ALL, "); from ws2s, the conversion fails.
about setlocale this piece is not familiar, man manual read a little dizzy, I would like to ask the following two function writing is not a problem, the use of setlocale will not change some behavior of the system, affect the operation of other programs, can setlocale mention that the main function is only executed once at the beginning of the program, rather than once each time the function is called?
man manual has the following contents:
If locale is an empty string, ", each part of the locale that should
be modified is set according to the environment variables. The
details are implementation-dependent.
Does mean that if I run on different computers, the results of the program may be different? how can I be sure? For example, I want to convert wchar and char to deal with Chinese in xml, because the tinyxml2 interface is char, so I need to convert.
/*
string converts to wstring
*/
std::wstring s2ws(const std::string& src)
{
std::wstring res = L"";
size_t const wcs_len = mbstowcs(NULL, src.c_str(), 0);
std::vector<wchar_t> buffer(wcs_len + 1);
mbstowcs(&buffer[0], src.c_str(), src.size());
res.assign(buffer.begin(), buffer.end() - 1);
return res;
}
/*
wstring converts to string
*/
std::string ws2s(const std::wstring & src)
{
setlocale(LC_ALL,"");
std::string res = "";
size_t const mbs_len = wcstombs(NULL, src.c_str(), 0);
std::vector<char> buffer(mbs_len + 1);
wcstombs(&buffer[0], src.c_str(), buffer.size());
res.assign(buffer.begin(), buffer.end() - 1);
return res;
}