c++c++23wstring

How can I std::print a std::wstring?


How do I print a wstring with std::print?

I have tried:

#include <print>
#include <string>
int main()
{
    std::wstring s = L"something";
    std::print(L"{}", s);
}

Try it online: https://godbolt.org/z/KWfYznTMj

With the Clang compiler error message being:

error: no matching function for call to 'print'
6 | std::print(L"{}", s);

Expected output: the code compiles and prints

something

I have tried:


Solution

  • You cannot directly use the functions in <print> to print out a std::wstring. The proposal P2093R14 intentionally omitted this functionality:

    Adding charN_t and wchar_t overloads will be explored in a separate paper in a more general context.

    Note that supporting wchar_t would either require calling the appropriate system API that can take wchar_t directly, or transcoding to Unicode/current locale and printing out the transcoded string. In any case, it's not trivial.

    There was quite a lot of discussion on the topic of std::wprint/std::print<wchar_t> on [std-proposals] recently; see https://lists.isocpp.org/std-proposals/2025/03/13201.php To my knowledge, no proposal was actually published though.

    Omitting L would also not work because std::print and std::format aren't capable of transcoding wchar_t strings into char strings, and that's what you're effectively requesting. See also Does std::format() accept different string types for format and arguments?

    Workaround

    For the time being, you'll just have to use std::wcout. Note that you can use std::wcout with std::format:

    std::wcout << std::format(L"{}\n", s);
    

    However, this isn't quite as good as a hypothetical std::wprint function; it doesn't attempt to dispatch to Unicode-handling functions like std::print does, and so you might get "mojibake" if you don't set up the locale properly.