如何將 std::string 轉換為 C++ 中的 LPCWSTR?


在本節中,我們將瞭解如何將 C++ 寬字串 (std::wstring) 轉換為 LPCWSTR。LPCWSTR 是(指向常寬字串的長指標)。它基本上是包含寬字元的字串。因此,透過將寬字串轉換為寬字元陣列,我們可以獲得 LPCWSTR。此 LPCWSTR 由 Microsoft 定義。所以為了使用它們,我們必須將 Windows.h 標頭檔案包含到我們的程式中。

要將 std::wstring 轉換為寬字元陣列型別字串,我們可以使用名為 c_str() 的函式以使其成為 C 語言形式的字串並指向寬字元字串。

示例程式碼

#include<iostream>
#include<Windows.h>
using namespace std;
main(){
   wstring my_str = L"Hello World";
   LPCWSTR wide_string ; //define an array with size of my_str + 1
   wide_string = my_str.c_str();
   wcout << "my_str is : " << my_str <<endl;
   wcout << "Wide String is : " << wide_string <<endl;
}

輸出

my_str is : Hello World
Wide String is : Hello World

更新於: 2019 年 7 月 30 日

3K+ 次瀏覽

點亮你的 職業生涯

完成課程後獲得認證

開始
廣告