【发布时间】:2011-03-05 17:22:45
【问题描述】:
char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);
我不能在
中使用cmd
sei.lpFile = cmad;
所以,
如何将char 数组转换为wchar_t 数组?
【问题讨论】:
char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);
我不能在
中使用cmd
sei.lpFile = cmad;
所以,
如何将char 数组转换为wchar_t 数组?
【问题讨论】:
就用这个吧:
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;
}
【讨论】:
std::unique_ptr<wchar_t[]> wa(new wchar_t[size]),您以后不必手动删除它。
来自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;
}
【讨论】:
从您的示例中使用swprintf_s 会起作用
wchar_t wcmd[40];
driver = FuncGetDrive(driver);
swprintf_s(wcmd, "%C:\\test.exe", driver);
注意%C 中的 C 必须大写,因为驱动程序是普通字符而不是 wchar_t。
将您的字符串传递给 swprintf_s(wcmd,"%S",cmd) 也应该可以工作
【讨论】: