Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีแปลง std::string เป็น LPCSTR ใน C++

บทนำ

ในส่วนนี้เราจะดูวิธีแปลง C++ string (std::string) เป็น LPCSTR (Long Pointer to Constant STRing) ซึ่งเป็นสตริงแบบ C โดยแปลง string เป็น character array ได้ LPCSTR เป็นของ Microsoft ต้อง include Windows.h

ใช้ฟังก์ชัน c_str() เพื่อแปลง std::string เป็น C-style string

ตัวอย่างโค้ด

#include <iostream>
#include <Windows.h>
using namespace std;

int main() {
    string my_str = "Hello World";
    LPTSTR long_string = new TCHAR[my_str.size() + 1];
    strcpy(long_string, my_str.c_str());
    cout << "my_str is : " << my_str << endl;
    cout << "Long String is : " << long_string << endl;
    return 0;
}

ผลลัพธ์

my_str is : Hello World
Long String is : Hello World