How to print UTF-8 strings to std::cout on Windows?

后端 未结 7 1211
南旧
南旧 2020-12-08 07:11

I\'m writing a cross-platform application in C++. All strings are UTF-8-encoded internally. Consider the following simplified code:

#include 
#         


        
7条回答
  •  失恋的感觉
    2020-12-08 08:02

    I had the same problem and wrote a very small library called libpu8 for this: https://github.com/jofeu/libpu8

    For windows consoles, it replaces the streambufs of cin, cout and cerr so that they accept and produce utf-8 at the front end and talk to the console in UTF-16. On non-windows operating systems, or if cin, cout, cerr are attached to files/pipes and not consoles, it does nothing. It also translates the arguments of the C++ main() function to UTF-8 on windows.

    Usage Example:

    #include 
    #include 
    #include 
    #include 
    
    // argv are utf-8 strings when you use main_utf8 instead of main.
    // main_utf8 is a macro. On Windows, it expands to a wmain that calls
    // main_utf8 with converted strings.
    int main_utf8(int argc, char** argv)
    {
            // this will also work on a non-Windows OS that supports utf-8 natively
            std::ofstream f(u8widen(argv[1]));
            if (!f)
            {
                    // On Windows, use the "W" functions of the windows-api together
                    // with u8widen and u8narrow
                    MessageBoxW(0,
                            u8widen(std::string("Failed to open file ") + argv[1]).c_str(), 0, 0);
                    return 1;
            }
            std::string line;
            // line will be utf-8 encoded regardless of whether cin is attached to a
            // console, or a utf-8 file or pipe.
            std::getline(std::cin, line);
            // line will be displayed correctly on a console, and will be utf-8 if
            // cout is attached to a file or pipe.
            std::cout << "You said: " << line;
            return 0;
    }
    

提交回复
热议问题