0

我是一个初学者cpp程序员。我正在将字符串值转换为 LPCWSTR。当我试图访问这个值时,它给出了一个空值。请检查下面附加的此代码。我认为这是因为内存引用值在变量范围之后被清除。

std::wstring string2wString(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

void main(){
    string str1,str2,str3;
    wstring wStr1;
    LPCWSTR lpStr1[MAX_PATH];
    int index=0;
    for(int i=0;i<iLimit;i++)
    {
        str1="String 1";
        //do operations
        for(int j=0;j<jLimit;j++)
        {
            // do operations
            str2=" String 2";
            str3= str1+str2;
            wStr1= string2wString(str3); //converting to wstring
            lpStr1[index]=wStr1.c_str();
            index++
        }
    }
    cout << lpStr1[0] << endl;
}

请帮我解决这个问题。

4

4 回答 4

1

后面修改时返回的指针wStr1.c_str()可能会失效。wStr1

最好的解决方法是坚持使用 C++ 类型:

std::wstring strings[MAX_PATH];

// ...
MultiByteToWideChar(CP_ACP, 0, str3.c_str(), slength, buf, len);
strings[index] = buf;
delete[] buf;
// ...

或者,您可以推迟删除缓冲区并在数组中使用它:

LPCWSTR lpStr1[MAX_PATH];
// ...
wchar_t* buf = new wchar_t[len];   
MultiByteToWideChar(CP_ACP, 0, str3.c_str(), slength, buf, len);
lpStr1[index] = buf;
于 2015-04-07T14:09:40.057 回答
0

这里有几个问题:

  • LPCWSTR lpStr1[MAX_PATH];正在定义一个指向 的指针数组const wchar_t,而不是const wchar_t您毫无疑问想要的数组。
  • lpStr1[index]=wStr1.c_str();正在存储指向由 .返回的临时缓冲区c_str()的指针。这不会将字符串复制到lpStr[index].
  • 我不确定 iLimit 和 jLimit 是什么,但如果您真的只想将字符串值转换为宽字符数组,我看不出这些循环打算完成什么。
于 2015-04-07T14:10:21.953 回答
0

我建议使用以下例程进行 UNICODE 转换:

wstring AsciiToUtf16(const string & str)
{
   if (str.empty())
      return wstring();

   size_t charsNeeded = ::MultiByteToWideChar(CP_ACP, 0, 
      str.data(), (int)str.size(), NULL, 0);
   if (charsNeeded == 0)
      throw runtime_error("Failed converting ASCII string to UTF-16");

   vector<wchar_t> buffer(charsNeeded);
   int charsConverted = ::MultiByteToWideChar(CP_ACP, 0, 
      str.data(), (int)str.size(), &buffer[0], buffer.size());
   if (charsConverted == 0)
      throw runtime_error("Failed converting ASCII string to UTF-16");

   return wstring(&buffer[0], charsConverted);
}
于 2015-04-07T14:13:18.187 回答
0

为什么不遵循这个:

C++ 将字符串(或 char*)转换为 wstring(或 wchar_t*)

完全忘记 LPCWSTR?

于 2015-04-07T14:16:10.157 回答