ในส่วนนี้เราจะมาดูวิธีการแปลงสตริง C++ (std::string) เป็น LPCSTR LPCSTR คือ (ตัวชี้แบบยาวถึงค่า STR คงที่) โดยพื้นฐานแล้วมันเป็นสตริงเช่น C ดังนั้นโดยการแปลงสตริงเป็นอาร์เรย์อักขระ เราจะได้รับ LPCSTR LPCSTR นี้กำหนดโดย Microsoft ดังนั้นหากต้องการใช้งาน เราต้องรวมไฟล์ส่วนหัวของ Windows.h ไว้ในโปรแกรมของเรา
ในการแปลง std::string เป็น C เช่น string เราสามารถใช้ฟังก์ชันที่เรียกว่า c_str()
โค้ดตัวอย่าง
#include<iostream>
#include<Windows.h>
using namespace std;
main() {
string my_str = "Hello World";
LPTSTR long_string = new TCHAR[my_str.size() + 1]; //define
an array with size of my_str + 1
strcpy(long_string, my_str.c_str());
cout << "my_str is : " << my_str <<endl;
cout << "Long String is : " << long_string <<endl;
} ผลลัพธ์
my_str is : Hello World Long String is : Hello World