char配列をwchar_tアレイに変換する方法は?
質問
char cmd[40];
driver = FuncGetDrive(driver);
sprintf_s(cmd, "%c:\\test.exe", driver);
使用できません cmd
の
sei.lpFile = cmad;
だから、変換する方法 char
アレイへ wchar_t
配列 ?
解決
から 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;
}
他のヒント
これを使用するだけです:
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;
}
このリンク 興味のあるものを含む多くの種類の文字列変換の例があります(MBSTOWCS_Sを探してください)
使用した例から swprintf_s うまくいきます
wchar_t wcmd[40];
driver = FuncGetDrive(driver);
swprintf_s(wcmd, "%C:\\test.exe", driver);
Cに注意してください %c ドライバーは通常のcharであり、wchar_tではなく通常のcharであるため、大文字で書く必要があります。
文字列をswprintf_s(wcmd、 "%s"、cmd)に渡すことも機能します
所属していません StackOverflow