Compare C-string of types char* and wchar_t* [closed]

[亡魂溺海] 提交于 2019-12-11 08:34:11

问题


I have a key like:

wchar_t key[] = L"764frtfg88fgt320nolmo098vfr"; 

and a char* row[i] returned by a query from a Database.

I'd like to compare my Key with row[i]. I tried with

wcscmp (key,row[i]) != 0)

but it gives me an error. Any suggestions ?


回答1:


This might help: C++ Convert string (or char*) to wstring (or wchar_t*)

As a summary:

#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;
}



回答2:


I'd use C++ tools:

#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";
}

Prints

false
true

Its perks are that it (should) work(s) with non-ASCII characters on both *nix and windows.




回答3:


There are other answers already but you could also convert char* to wchat_t* like this.

Declare the following:

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;
}

Then use it like this:

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);

Say thanks to this thread: How to convert char* to wchar_t*?



来源:https://stackoverflow.com/questions/41876355/compare-c-string-of-types-char-and-wchar-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!