How to Convert wstring to string in C++?
Last Updated :
19 Jul, 2024
std::wstring in C++, is a wide string type where each character is a wide character, typically used for internationalization. Sometimes, we need to convert a std::wstring to a std::string for compatibility with functions that only accept narrow strings. In this article, we will learn how to convert a std::wstring to a std::string in C++.
Example:
Input:
wstring wstr = L"Hello, World!";
Output:
string str = "Hello, World!";
Converting std::wstring to std::string in C++
To convert a std::wstring to a std::string in C++, we can use the std::wcstombs function from the <cstdlib> library that converts a wide-character string to a multibyte character string or the std::wstring_convert class from the <locale> library. However, starting from C++17, std::wstring_convert and std::codecvt are deprecated. Therefore, a better approach is to use the td::wcstombs function.
Syntax to Use std::wcstombs Function
size_t wcstombs(char* dest, const wchar_t* src, size_t max);
Here,
- dest: Pointer to a char array where the result will be stored.
- src: Pointer to the null-terminated wide string to be converted.
- max: Maximum number of bytes to be written to the destination array.
C++ Program to Convert std::wstring to std::string
The below program demonstrates how we can convert a wide string to a narrow string using the std::wcstombs function in C++.
C++
// C++ program to illustrate how to convert std::wstring to
// std::string
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Creating wstring
wstring wstr = L"Hello, World!";
// Calculating the length of the multibyte string
size_t len = wcstombs(nullptr, wstr.c_str(), 0) + 1;
// Creating a buffer to hold the multibyte string
char* buffer = new char[len];
// Converting wstring to string
wcstombs(buffer, wstr.c_str(), len);
// Creating std::string from char buffer
string str(buffer);
// Cleaning up the buffer
delete[] buffer;
// Print the string
cout << "String: " << str << endl;
return 0;
}
OutputString: Hello, World!
Time Complexity: O(N), where N is the size of the wide string.
Auxiliary Space: O(N), where N is the size of the resulting narrow string.