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



std::string

The std::string is a class of C++ Standard Library (STL) that represents a string (sequence of characters). It is used to handle strings with better memory management, i.e., it provides dynamic memory management for strings and supports a rich set of in-built functions for string manipulation.

Syntax

Following is the syntax of string:

string str = "tutorialspoint";

std::LPCSTR

LPCSTR stands for Long Pointer to Constant String. It is a constant, null-terminated string of ANSI (narrow) characters (8-bit characters). In contrast to LPCWSTR, which stores wide characters (Unicode/UTF-16), LPCSTR is used in Windows API functions to store regular char-based strings.

Syntax

Following is the syntax of LPCSTR:

LPCSTR str = "tutorialspoint";

Since LPCSTR is defined by Microsoft developers are required to use the <window.h> header file to use LPCSTR string.

Converting std::string to LPCSTR

Following is the steps to convert a string to LPCSTR:

  • We apply c_str() method on the returned string object. It will return the equivalent of the LPCSTR string.

C++ Program to Convert String to LPCSTR

In the following example, we create a C++ program that converts a std::string to an LPCSTR string:

#include <windows.h>
#include <windows.h>
#include <iostream>
using namespace std;
int main()
{
   // An string object
   string myString = "tutorialspoint";
   
   // Applying c_str() method on wstr
   LPCSTR lpcstr = myString.c_str();
   
   cout << "str is : " << str << endl;
   wcout << "lpcstr is : "<< lpcstr << endl;
}

Following is the output. Note that this code will work only with Microsoft Visual Studio or MinGW because these support Windows.h which is only available in Windows environments.

str is: "tutorialspoint.com"
lpcstr is: "tutorialspoint.com"
Updated on: 2025-06-04T17:51:29+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements