如何将char数组转换为wchar_t数组?

pra*_*eep 10 c++ arrays wchar-t char

char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);
Run Code Online (Sandbox Code Playgroud)

我不能用cmd

sei.lpFile = cmad;
Run Code Online (Sandbox Code Playgroud)

那么,如何将char数组转换为wchar_t数组呢?

lee*_*ade 20

只要用这个:

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;
}
Run Code Online (Sandbox Code Playgroud)

完成后不要忘记调用delete [] wCharPtr返回结果,否则如果你在没有清理的情况下继续调用它,这是一个等待发生的内存泄漏.或者像下面的评论者所建议的那样使用智能指针.

或者使用标准字符串,如下所示:

#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;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您使用`std :: unique_ptr &lt;wchar_t []&gt; wa(new wchar_t [size])`,则以后不必手动删除它。 (2认同)
  • 由于wchar_t已经具有带有std :: wstring的标准资源管理器,因此也可以代替智能指针使用它。 (2认同)

Tra*_*Guy 16

来自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;
}
Run Code Online (Sandbox Code Playgroud)

  • 谢谢.我应该链接到谷歌以及:) (6认同)
  • 您应链接到您的来源:http://msdn.microsoft.com/en-us/library/ms235631%28VS.80%29.aspx (2认同)