且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Windows控制台上输出Unicode字符串

更新时间:2021-09-28 21:31:07

我/我们在大多数(跨平台)应用程序/项目中使用的一般策略是:我们只使用UTF-8(我的意思是真正的标准)无处不在。我们使用std :: string作为容器,我们只是将一切解释为UTF8。而且我们还以这种方式处理所有文件IO,即我们希望使用UTF8并保存UTF8。如果我们从某个地方得到一个字符串并且我们知道它不是UTF8,我们将其转换为UTF8。

The general strategy I/we use in most (cross platform) applications/projects is: We just use UTF-8 (I mean the real standard) everywhere. We use std::string as the container and we just interpret everything as UTF8. And we also handle all file IO this way, i.e. we expect UTF8 and save UTF8. In the case when we get a string from somewhere and we know that it is not UTF8, we will convert it to UTF8.

最常见的情况是偶然碰到WinUTF16用于文件名。因此,对于每个文件名处理,我们将始终将UTF8字符串转换为WinUTF16。

The most common case where we stumble upon WinUTF16 is for filenames. So for every filename handling, we will always convert the UTF8 string to WinUTF16. And also the other way if we search through a directory for files.

控制台在我们的Windows版本中并没有真正使用(在Windows版本中,所有控制台输出都是包装成文件)。由于我们到处都有UTF8,因此控制台输出也是UTF8,这对于大多数现代系统都很好。而且Windows控制台日志文件在UTF8中具有其内容,Windows上的大多数文本编辑器都可以毫无问题地读取它。

The console isn't really used in our Windows build (in the Windows build, all console output is wrapped into a file). As we have UTF8 everywhere, also our console output is UTF8 which is fine for most modern systems. And also the Windows console log file has its content in UTF8 and most text-editors on Windows can read that without problems.

如果我们更多地使用WinConsole,并且会非常在意所有特殊字符是否正确显示,我们可能会编写一些自动管道处理程序,将其安装在 fileno = 0 和实际的之间stdout ,它将按照您的建议使用 WriteConsoleW (如果确实没有更简单的方法)。

If we would use the WinConsole more and if we would care a lot that all special chars are displayed correctly, we maybe would write some automatic pipe handler which we install in between fileno=0 and the real stdout which will use WriteConsoleW as you have suggested (if there is really no easier way).

如果您想知道如何实现这种自动管道处理程序:我们已经为所有类似POSIX的系统实现了这种方法。该代码可能无法在Windows上正常运行,但我认为应该可以移植它。我们当前的管道处理程序类似于 tee 所做的事情。即如果您执行 cout<< 你好<< endl ,它将同时打印在 stdout 和某些日志文件中。查看代码,如果您对此感兴趣的话。

If you wonder about how to realize such automatic pipe handler: We have implemented such thing already for all POSIX-like systems. The code probably doesn't work on Windows as it is but I think it should be possible to port it. Our current pipe handler is similar to what tee does. I.e. if you do a cout << "Hello" << endl, it will both be printed on stdout and in some log-file. Look at the code if you are interested how this is done.