如何将字符数组转换为宽字符数组?

10
char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);

我无法在命令提示符中使用 cmd

sei.lpFile = cmad;

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

3个回答

23

只需使用以下代码:

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

在使用完返回结果后,不要忘记调用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;
}

2
如果您使用 std::unique_ptr<wchar_t[]> wa(new wchar_t[size]),那么您就不必手动删除它。 - a paid nerd
2
由于wchar_t已经具有带有std::wstring的标准资源管理器,因此它也可以用作智能指针的替代品。 - Robert

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

0

从你的例子来看,使用swprintf_s会起作用。

wchar_t wcmd[40];
driver = FuncGetDrive(driver);
swprintf_s(wcmd, "%C:\\test.exe", driver);

请注意,%C 中的 C 必须大写,因为 driver 是普通字符而不是 wchar_t。
将字符串传递给 swprintf_s(wcmd,"%S",cmd) 也应该可以正常工作。

@rajivpradeep 这就是我的意思,大写的C而不是小写的c是指字符。 - josefx

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接