how to convert char array to wchar_t array?

后端 未结 3 2024
情书的邮戳
情书的邮戳 2020-12-10 14:27
char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, \"%c:\\\\test.exe\", driver);

I cannot use cmd in

sei.lpF         


        
3条回答
  •  死守一世寂寞
    2020-12-10 15:11

    Just use this:

    static wchar_t* charToWChar(const char* text)
    {
        const size_t size = strlen(text) + 1;
        wchar_t* wText = new wchar_t[size];
        mbstowcs(wText, text, size);
        return wText;
    }
    

    Don't forget to call delete [] wCharPtr on the return result when you're done, otherwise this is a memory leak waiting to happen if you keep calling this without clean-up. Or use a smart pointer like the below commenter suggests.

    Or use standard strings, like as follows:

    #include 
    #include 
    #include 
    
    static std::wstring charToWString(const char* text)
    {
        const size_t size = std::strlen(text);
        std::wstring wstr;
        if (size > 0) {
            wstr.resize(size);
            std::mbstowcs(&wstr[0], text, size);
        }
        return wstr;
    }
    

提交回复
热议问题