Home > Backend Development > C++ > How can I efficiently convert a `wstring` to a `string` in C ?

How can I efficiently convert a `wstring` to a `string` in C ?

DDD
Release: 2024-12-14 15:08:11
Original
699 people have browsed it

How can I efficiently convert a `wstring` to a `string` in C  ?

Converting wstring to string in C

Issue

How can I convert a wstring to a string in C ? Consider the following example:

#include <string>
#include <iostream>

int main() {
    std::wstring ws = L"Hello";
    std::string s(ws.begin(), ws.end());

    std::cout << "std::string =     " << s << std::endl;
    std::wcout << "std::wstring =    " << ws << std::endl;
    std::cout << "std::string =     " << s << std::endl;
}
Copy after login

With the commented-out line, the output is:

std::string =     Hello
std::wstring =    Hello
std::string =     Hello
Copy after login

However, without it, the output is only:

std::wstring =    Hello
Copy after login

Answer

Using std::wstring_convert (C 11)

As pointed out by Cubbi, std::wstring_convert provides an easy solution:

#include <locale>
#include <codecvt>

std::wstring string_to_convert;

using convert_type = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_type, wchar_t> converter;

// Convert wstring to string
std::string converted_str = converter.to_bytes(string_to_convert);
Copy after login

You can also use helper functions to simplify the conversion:

// Convert string to wstring
std::wstring s2ws(const std::string& str) {
    using convert_typeX = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_typeX, wchar_t> converterX;
    return converterX.from_bytes(str);
}

// Convert wstring to string
std::string ws2s(const std::wstring& wstr) {
    using convert_typeX = std::codecvt_utf8<wchar_t>;
    std::wstring_convert<convert_typeX, wchar_t> converterX;
    return converterX.to_bytes(wstr);
}
Copy after login

The above is the detailed content of How can I efficiently convert a `wstring` to a `string` in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template