在本节中,我们将看到如何将C ++字符串(std::string)转换为LPCSTR。LPCSTR是(常量STRing的长指针)。它基本上是类似于C的字符串。因此,通过将字符串转换为字符数组,我们可以获得LPCSTR。该LPCSTR是Microsoft定义的。因此,要使用它们,我们必须在程序中包含Windows.h头文件。
要将std::string转换为类似于字符串的C,我们可以使用名为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