简体   繁体   中英

How to correctly display strings in user preferred locale in C++?

I posted this code in another question :

 auto operator<<(std::ostream& out, const std::u8string_view str) -> std::ostream& { std::locale::global(std::locale{".utf8"}); auto& ret = out << std::string_view{std::bit_cast<const char*>(str.data()), str.size()}; std::locale::global(std::locale{""}); return ret; }

I intended to convert u8string to a user-preferred locale before printing. But in this answer to that post, @Chronial pointed out that I was using the global locale wrongly.

I thought outstreams interpret the data in the global encoding and convert it to the imbue 'd encoding while writing. So, since the data I'm feeding is in utf8 and I want to display it in a user-preferred locale, I changed global and didn't touch imbue in the above code.

For Eg: If my terminal is using EBCDIC and I have ASCII strings in my application, what is the correct procedure to display them properly? Displaying them directly would produce gibberish, AFAIK.

What I thought is, if I set global to ASCII and imbue to EBCDIC , this will make the stream interpret data as ASCII and convert it to EBCDIC before printing.

The above scenario of converting from ASCII to EBCDIC is just taken as an example. I was seeking for a generic solution, not just for the case of ASCII to EBCDIC .

The C++ standard library is not really designed to help you in this scenario. You either have to handle the re-encoding yourself or use wide character streams. You will then have do decode your strings into wide character strings, write these to the stream and the stream will then use the locale/encoding it is imbued with to reencode the string.

But kind of app are you writing exactly that this actually matters to you? For most applications it should be fine to just write UTF8, since that is what all modern terminals should be configured to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM