how to convert char array to wchar_t array?

52,143

Solution 1

From MSDN:

#include <iostream>
#include <stdlib.h>
#include <string>

using namespace std;
using namespace System;

int main()
{
    char *orig = "Hello, World!";
    cout << orig << " (char *)" << endl;

    // Convert to a wchar_t*
    size_t origsize = strlen(orig) + 1;
    const size_t newsize = 100;
    size_t convertedChars = 0;
    wchar_t wcstring[newsize];
    mbstowcs_s(&convertedChars, wcstring, origsize, orig, _TRUNCATE);
    wcscat_s(wcstring, L" (wchar_t *)");
    wcout << wcstring << endl;
}

Solution 2

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 <cstdlib>
#include <cstring>
#include <string>

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;
}
Share:
52,143
pradeep
Author by

pradeep

Updated on July 16, 2022

Comments

  • pradeep
    pradeep over 1 year
    char cmd[40];
    driver = FuncGetDrive(driver);
    sprintf_s(cmd, "%c:\\test.exe", driver);
    

    I cannot use cmd in

    sei.lpFile = cmad;
    

    so, how to convert char array to wchar_t array ?

  • On Freund
    On Freund over 13 years
  • josefx
    josefx over 13 years
    @rajivpradeep which is what I meant, the uppercase C instead of c is for char
  • a paid nerd
    a paid nerd over 8 years
    If you use std::unique_ptr<wchar_t[]> wa(new wchar_t[size]) you won't have to manually delete it later.
  • Robert
    Robert over 7 years
    Since wchar_t already has a standard resource manager with std::wstring, it can be used instead of a smart pointer, too.