Initialize a wchar_t[] using a string

时间:2018-07-25 04:55:42

标签: c++ string wmi

Currently, I'm dealing with WMI for collecting the log files from a remote machine. I have the username of the remote machine initialized as given below.

wchar_t pszName[]=L"My username";

pszName[] is a wchar_t array. The trouble I face is that when I pass my username as a parameter of string datatype, I need to initialize wchar_t array using a string.

I cannot use a wchar_t* pointer because it gives me an error on the later part of the program. I need to initialize something like

string username = "My username";
wchar_t pszName[] = .....?.....;

2 个答案:

答案 0 :(得分:0)

#include <string>
#include <vector>
#include <windows.h>

std::wstring str_to_wstr(std::string const & str)
{
    int length = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), 0, 0);
    if (!length)
        return L"utf-8 to utf-16 conversion error!";

    std::vector<wchar_t> buffer(length + 1);
    if (!MultiByteToWideChar(CP_UTF8, 0, str.c_str(), str.length(), buffer.data(), length))
        return L"utf-8 to utf-16 conversion error!";

    return std::wstring(buffer.data(), length);
}

// ...

std::string username{ "My username" };
std::wstring utf_16_username{ str_to_wstr(username) };

// ... use:
utf_16_username.data();  // wherever you would have used pszName

答案 1 :(得分:0)

您可以使用std::mbstowcs function将字符串转换为wchar_t*

std::string username = "My username"; //set your username
wchar_t pszName[] = L"My username";   //initialize pszName with a certain length wide string
std::mbstowcs(pszName, name.c_str(), std::wcslen(pszName)); //copy and convert name from username to pszName

您需要包括:

#include <string>
#include <cstdlib>

请注意,您必须为pszName指定一个最大长度,并且实际上该值必须至少在内存中分配了该长度!否则会导致运行时崩溃!

在当前的实现中,您只需在pszName中插入正确长度的虚拟名称,并使用std::wcslen function获得正确的长度。