Skip to content
Related Articles
Open in App
Not now

Related Articles

Convert std::string to LPCWSTR in C++

Improve Article
Save Article
  • Last Updated : 20 Oct, 2022
Improve Article
Save Article

C++ provides us a facility using which one can represent a sequence of characters as an object of a class. This class is std::string. Internally, std::string class represents a string as a sequence of characters (bytes) and each character can be accessed using the [] operator.

The difference between a character array and a string is that a character array is simply an array of characters terminated with a null character whereas a string class is part of the C++ library that gives us the functionality to create objects in which we can store string literals easily. A string can be declared and initialized by using the below syntax,

Syntax:

string str = “GeeksforGeeks”;

std::LPCWSTR

LPCWSTR stands for Long Pointer to Constant Wide STRing. It is a 32-bit pointer to a constant string of 16-bit Unicode characters, which may be null-terminated. In simple words, it is the same as a string but with wide characters. 

Syntax:

 LPCWSTR str = “GeeksforGeeks”;

This string is Microsoft defined and programmers are required to include <Window.h> header file to use LPCWSTR strings. This article focuses on how to convert std::string to LPCWSTR in C++ (Unicode).

Converting a std::string to LPCWSTR in C++ (Unicode)

Converting a string to LPCWSTR is a two-step process.

Step1: First step is to convert the initialized object of the String class into a wstring. std::wstring is used for wide-character/Unicode (UTF-16) strings. The transformation can be easily done by passing endpoint iterators of the given string to the std::wstring() initializer.

std::wstring(str.begin(), str.end())

It returns a wstring object.

Step 2: Next step is to apply the c_str() method on the returned wstring object (obtained from step1). It will return the equivalent LPCWSTR string. The above process has been demonstrated through the below source code.

Below is the C++ program to implement the above approach-

C++




// C++ program to illustrate how to
// convert std:: string to LPCWSTR
 
#include <Windows.h>
#include <iostream>
 
using namespace std;
 
int main()
{
 
    // Initializing a string object
    string str = "GeeksforGeeks";
 
    // Initializing an object of wstring
    wstring temp = wstring(str.begin(), str.end());
 
    // Applying c_str() method on temp
    LPCWSTR wideString = temp.c_str();
 
    // Print strings
    cout << "str is : " << str << endl;
    wcout << "wideString is : "
          << wideString << endl;
}


Output:

str is: “GeeksforGeeks”

wideString is: “GeeksforGeeks”

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!