
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert std::string to LPCWSTR 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::LPCWSTR
The LPCWSTR stands for Long Pointer to Constant Wide STRing. It is a constant string of 16-bit Unicode characters, which may be null-terminated. It is the same as a string but with wide characters.
Syntax
Following is the syntax of LPCWSTR:
LPCWSTR str = "tutorialspoint";
Since LPCWSTR is defined by Microsoft developers are required to use the <window.h> header file to use LPCWSTR string.
Converting std::string to LPCWSTR
Following are the steps to convert a string to LPCWSTR:
Step 1: The initial work is to initialize an object of String class into a wstring. std::wstring is used for wide character/Unicode (UTF-16) String. So, the transformation is as easy as passing endpoint iterators from the given string to the std::wstring() initializer.
std::wstring(str.begin(), str.end())It returns a wstring object.
Step 2: Here, in the step, we apply c_str() method on the returned string object. It will return the equivalent of the LPCWSTR string.
C++ Program to Convert String to LPCWSTR
In the following example, we create a C++ program that converts a std::string to an LPCWSTR string:
#include <windows.h> #include <iostream> using namespace std; int main() { // An string object string str = "tutorialspoint.com"; // An object of wstring wstring wstr = wstring(str.begin(), str.end()); // Applying c_str() method on wstr LPCWSTR wideString = wstr.c_str(); cout << "str is : " << str << endl; wcout << "wideString is : "<< wideString << 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" wideString is: "tutorialspoint.com"