c++ - How to compare a wstring with a _T("some String")? -
i have functionwstring a2t(const string& str)
convert string
wstring
. cannot correct value when compare return value const wstring
. example;
wstring stron = a2t("on"); if ( stron == _t("on")) { setitemswitch(true); } else { setitemswitch(false); }
the if(stron == _t("on"))
statement false. wrong code?
this a2t
:
std::wstring a2t(const string& str) { if (str.empty()) return std::wstring(); int sz = multibytetowidechar(cp_utf8, 0, str.c_str(), -1, 0, 0); std::wstring res(sz, 0); multibytetowidechar(cp_utf8, 0, &str[0], -1, &res[0], sz); return res; }
the issue in interpretation (or use of) of return value first call multibytetowidechar
- return size required buffer including terminating null
character. when creating wide string, count null
should removed size, string add internally.
in addition, on second call, use actual sizes of strings; avoid multibytetowidechar
processing buffer including terminating null
characters (their presence catered in string size calculations). again, strings manage null
internally.
std::wstring a2t(const std::string& str) { if (str.empty()) return std::wstring(); int sz = multibytetowidechar(cp_utf8, 0, str.c_str(), -1, 0, 0); std::wstring res(sz - 1, 0); // ^^^ count "remove" null multibytetowidechar(cp_utf8, 0, &str[0], str.size(), &res[0], res.size()); // ^^^ use actual sizes return res; }
depending on version of compiler being used, investigate use of std::basic_string::data
res.data()
on use of &res[0]
.
Comments
Post a Comment