Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

wstring

c++23

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:

  • removing L from the format string, just in case the format string can't be a std::wstring. I didn't hope for much, since typically the types of string need to match. And indeed, that gives error: call to deleted constructor of 'formatter<wstring, char>'
  • finding std::wprint on cppreference (google it).
  • finding an answer in this question, but std::print is not mentioned.
like image 573
Thomas Weller Avatar asked Dec 16 '25 23:12

Thomas Weller


1 Answers

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.

like image 72
Jan Schultke Avatar answered Dec 19 '25 12:12

Jan Schultke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!