如何使用go在Windows控制台中正确输出字符串?

我有一个exe可以打印utf-8编码的字符串的字符串,其中带有特殊字符。
由于该exe是从控制台窗口使用的,因此它的输出被修改了,因为Windows使用了ibm850编码(aka code page 850)。

您如何确保goexe为控制台窗口打印正确编码的字符串,例如,打印:

éèïöîôùòèìë

而不是(不对正确的字符集进行任何翻译)

├®├¿├»├Â├«├┤├╣├▓├¿├¼├½


饮歌长啸
浏览 298回答 3
3回答

慕桂英4014372

// Alert: This is Windows-specific, uses undocumented methods, does not// handle stdout redirection, does not check for errors, etc.// Use at your own risk.// Tested with Go 1.0.2-windows-amd64.package mainimport "unicode/utf16"import "syscall"import "unsafe"var modkernel32 = syscall.NewLazyDLL("kernel32.dll")var procWriteConsoleW = modkernel32.NewProc("WriteConsoleW")func consolePrintString(strUtf8 string) {&nbsp; &nbsp; var strUtf16 []uint16&nbsp; &nbsp; var charsWritten *uint32&nbsp; &nbsp; strUtf16 = utf16.Encode([]rune(strUtf8))&nbsp; &nbsp; if len(strUtf16) < 1 {&nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; }&nbsp; &nbsp; syscall.Syscall6(procWriteConsoleW.Addr(), 5,&nbsp; &nbsp; &nbsp; &nbsp; uintptr(syscall.Stdout),&nbsp; &nbsp; &nbsp; &nbsp; uintptr(unsafe.Pointer(&strUtf16[0])),&nbsp; &nbsp; &nbsp; &nbsp; uintptr(len(strUtf16)),&nbsp; &nbsp; &nbsp; &nbsp; uintptr(unsafe.Pointer(charsWritten)),&nbsp; &nbsp; &nbsp; &nbsp; uintptr(0),&nbsp; &nbsp; &nbsp; &nbsp; 0)}func main() {&nbsp; &nbsp; consolePrintString("Hello ☺\n")&nbsp; &nbsp; consolePrintString("éèïöîôùòèìë\n")}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go