我有key
喜欢:
wchar_t key[] = L"764frtfg88fgt320nolmo098vfr";
和来自数据库的查询返回的char* row[i]
。
我想将Key
与row[i]
进行比较。我试过
wcscmp (key,row[i]) != 0)
但它给了我一个错误。有什么建议吗?
答案 0 :(得分:1)
这可能会有所帮助:C++ Convert string (or char*) to wstring (or wchar_t*)
总结:
#include <string>
wchar_t Key[] = L"764frtfg88fgt320nolmo098vfr";
std::wstring k(Key);
const char* text = "test"; // your row[i]
std::string t(text);
// only works well if the string being converted contains only ASCII characters.
std::wstring a(t.begin(), t.end());
if(a.compare(k) == 0)
{
std::cout << "same" << std::endl;
}
答案 1 :(得分:0)
我使用的是C ++工具:
#include <iostream>
#include <string>
// construct a wstring from a string
std::wstring to_wstring(std::string const& str)
{
const size_t len = ::mbstowcs(nullptr, &str[0], 0);
if (len == size_t(-1)) {
throw std::runtime_error("to_wstring()");
}
std::wstring result(len, 0);
::mbstowcs(&result[0], &str[0], result.size());
return result;
}
//
// TEST CASES ---
//
const wchar_t key[] = L"764frtfg88fgt320nolmo098vfr";
const auto wkey = std::wstring(key);
bool operator==(std::string const& lhs, std::wstring const& rhs)
{
return to_wstring(lhs) == rhs;
}
bool operator==(std::wstring const& lhs, std::string const& rhs) { return rhs == lhs; }
int main() {
std::cout << std::boolalpha << ("hello" == wkey) << "\n"
<< (wkey == "764frtfg88fgt320nolmo098vfr") << "\n";
}
打印
false
true
它的好处是它(应该)在* nix和windows上使用非ASCII字符。
答案 2 :(得分:0)
还有其他答案,但您也可以像这样将char *转换为wchat_t *。
声明以下内容:
const wchar_t *GetWC(const char *c)
{
const size_t cSize = strlen(c)+1;
wchar_t* wc = new wchar_t[cSize];
mbstowcs (wc, c, cSize);
return wc;
}
然后像这样使用它:
wchar_t * temprow;
temprow = (wchar_t *)GetWC(row[i]);
/* replace following line with your own */
std::cout << "i " << i << " is " << (wcscmp (key,temprow) != 0) << "\n";
/* avoid memory leak */
free(temprow);