在 C 或 C++ 中是否有等效于 setvbuf() 的方法来处理宽字符?
Is there an equivalent to setvbuf() in C or C++ to handle wide characters?
C++ std::setvbuf
函数允许通过各种缓冲选项调节文件流。不过,该流只能处理普通的 char
s。是否有适用于宽字符 (wchar_t
) 的等效版本可用?
setvbuf
在 Windows 8+ 中工作,可以在控制台 window 中写入 UTF8。从 Windows 10 build 1803 开始,仍不支持读取 UTF8。
在 Visual Studio 中,您可以在控制台 window 中使用编译器特定 _setmode
到 read/write UTF16。但这在其他编译器中可能不是一个选项(我上次检查时 MinGW-32 不支持它)。唯一的其他选择是根据 WriteConsoleW
.
编写流函数
请注意,控制台 window 可能不支持在 0xFFFF
以上打印 Unicode 代码点,除非您使用 SetCurrentConsoleFontEx
将控制台字体更改为适当的字体,例如 "MS Gothic"
(仍然没有处理很多代码点)
#include <iostream>
#include <string>
#include <io.h>
#include <fcntl.h>
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stdin), _O_U16TEXT);
std::wcout << L"UTF16 English ελληνικά\n";
std::wstring utf16;
std::wcin >> utf16;
std::wcout << utf16 << "\n";
return 0;
}
C++ std::setvbuf
函数允许通过各种缓冲选项调节文件流。不过,该流只能处理普通的 char
s。是否有适用于宽字符 (wchar_t
) 的等效版本可用?
setvbuf
在 Windows 8+ 中工作,可以在控制台 window 中写入 UTF8。从 Windows 10 build 1803 开始,仍不支持读取 UTF8。
在 Visual Studio 中,您可以在控制台 window 中使用编译器特定 _setmode
到 read/write UTF16。但这在其他编译器中可能不是一个选项(我上次检查时 MinGW-32 不支持它)。唯一的其他选择是根据 WriteConsoleW
.
请注意,控制台 window 可能不支持在 0xFFFF
以上打印 Unicode 代码点,除非您使用 SetCurrentConsoleFontEx
将控制台字体更改为适当的字体,例如 "MS Gothic"
(仍然没有处理很多代码点)
#include <iostream>
#include <string>
#include <io.h>
#include <fcntl.h>
int main()
{
_setmode(_fileno(stdout), _O_U16TEXT);
_setmode(_fileno(stdin), _O_U16TEXT);
std::wcout << L"UTF16 English ελληνικά\n";
std::wstring utf16;
std::wcin >> utf16;
std::wcout << utf16 << "\n";
return 0;
}