How to convert std::string to LPCSTR in C++?


In this section we will see how to convert C++ string (std::string) to LPCSTR. The LPCSTR is the (Long Pointer to Constant STRing). It is basically the string like C. So by converting string to character array we can get LPCSTR. This LPCSTR is Microsoft defined. So to use them we have to include Windows.h header file into our program.

To convert std::string to C like string we can use the function called c_str().

Example Code

#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;
}

Output

my_str is : Hello World
Long String is : Hello World

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements