Hi
Does any buddy help me to convert char* to std::wstring

Dani AI

Generated

@%sundip Your iterator-ctor solution only widens bytes; it does not decode text. It will appear to work for plain 7-bit ASCII, but any UTF-8 or other multibyte input will be mangled. You need a real decoding step based on the source encoding.

On Windows, if your char* is UTF-8, use MultiByteToWideChar(CP_UTF8, ...) to produce a UTF-16 std::wstring. Pass MB_ERR_INVALID_CHARS to validate input and call once to size the buffer, then again to convert. Example:

#include <string>
#include <stdexcept>
#include <windows.h>

std::wstring utf8_to_wstring(const char* s) {
    if (!s) return {};
    int n = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s, -1, nullptr, 0);
    if (n <= 0) throw std::runtime_error("Invalid UTF-8");
    std::wstring w(n - 1, L'\0');            // -1 to drop the null
    MultiByteToWideChar(CP_UTF8, 0, s, -1, w.data(), n);
    return w;
}

MultiByteToWideChar maps a byte string to UTF-16; you can also use CP_ACP for the current ANSI code page, but prefer UTF-8 for reliability. (learn.microsoft.com)

For quick cross-platform code where the input is UTF-8, you can use the standard facet-based converter (note: deprecated since C++17 and removed in C++26), and plan a migration to a library like ICU, Boost.Nowide, or iconv:

#include <string>
#include <codecvt>
#include <locale>

std::wstring utf8_to_wstring_portable(const char* s) {
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv;
    return conv.from_bytes(s ? s : "");
}

std::wstring_convert and std::codecvt_* are deprecated, so treat this as a stopgap. (en.cppreference.com)

Finally, remember std::wstring stores wchar_t code units; their width/encoding is implementation-defined, which is why decoding from a known input encoding is essential. On Windows, those wide strings are UTF-16. (learn.microsoft.com)

I have got the answer

std::wstring ctow(const char* src)
{
    return std::wstring(src, src + strlen(src));
}

Thanks every one :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.