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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3074776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 12:00:18  来源:igfitidea点击:

how to convert char array to wchar_t array?

c++arrayscharwchar-t

提问by pradeep

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

I cannot use cmdin

我不能用cmd

sei.lpFile = cmad;

so, how to convert chararray to wchar_tarray ?

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

回答by leetNightshade

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 [] wCharPtron 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.

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

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

回答by Traveling Tech Guy

From MSDN:

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

回答by josefx

From your example using swprintf_swould work

从你的例子使用swprintf_s会工作

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

Note the C in %Chas to be written with uppercase since driver is a normal char and not a wchar_t.
Passing your string to swprintf_s(wcmd,"%S",cmd) should also work

请注意,%C 中的 C必须用大写字母书写,因为驱动程序是普通字符而不是 wchar_t。
将您的字符串传递给 swprintf_s(wcmd,"%S",cmd) 也应该有效