如何在Windows控制台中正确输出字符串? [英] How to properly output a string in a Windows console with go?
问题描述
我有一个 exe文件
,它会打印 utf- 8 编码的字符串,其中包含特殊字符。
由于该exe文件是在控制台窗口中使用的,因此它的输出被破坏,因为Windows使用 ibm850
encoding(又名
代码页850
)。
I have a exe
in go which prints utf-8 encoded strings, with special characters in it.
Since that exe is made to be used from a console window, its output is mangled because Windows uses ibm850
encoding (aka code page 850
).
您如何确保为控制台窗口打印正确编码的字符串 exe
,例如打印:
How would you make sure the go exe
print correctly encoded strings for a console windows, ie print for instance:
éèïöîôùòèìë
而不是(没有任何翻译权) charset )
instead of (without any translation to the right charset)
├®├¿├»├Â├«├┤├╣├▓├¿├¼├½
推荐答案
HTTP:// jan.newmarch.name/go/rel =nofollow>使用Go进行网络编程( CC BY-NC-SA 3.0 )有关于字符集的一章(管理字符集和编码),其中 Jan Newmarch 详细介绍将一个字符集转换为另一个字符。但看起来很麻烦。
The online book "Network programming with Go" (CC BY-NC-SA 3.0) has a chapter on Charsets (Managing character sets and encodings), in which Jan Newmarch details the conversion of one charset to another. But it seems cumbersome.
这是一个解决方案(我可能错过了一个更简单的解决方案),使用库 go-charset (来自 Roger Peppe )。
我将 utf-8
字符串转换为 ibm850
编码一个,允许我在DOS窗口中打印:
Here is a solution (I might have missed a much simpler one), using the library go-charset (from Roger Peppe).
I translate an utf-8
string to an ibm850
encoded one, allowing me to print in a DOS windows:
éèïöîôùòèìë
翻译功能如下:
The translation function is detailed below:
package main
import (
"bytes"
"code.google.com/p/go-charset/charset"
_ "code.google.com/p/go-charset/data"
"fmt"
"io"
"log"
"strings"
)
func translate(tr charset.Translator, in string) (string, error) {
var buf bytes.Buffer
r := charset.NewTranslatingReader(strings.NewReader(in), tr)
_, err := io.Copy(&buf, r)
if err != nil {
return "", err
}
return string(buf.Bytes()), nil
}
func Utf2dos(in string) string {
dosCharset := "ibm850"
cs := charset.Info(dosCharset)
if cs == nil {
log.Fatal("no info found for %q", dosCharset)
}
fromtr, err := charset.TranslatorTo(dosCharset)
if err != nil {
log.Fatal("error making translator from %q: %v", dosCharset, err)
}
out, err := translate(fromtr, in)
if err != nil {
log.Fatal("error translating from %q: %v", dosCharset, err)
}
return out
}
func main() {
test := "éèïöîôùòèìë"
fmt.Println("utf-8:\n", test)
fmt.Println("ibm850:\n", Utf2dos(test))
}
这篇关于如何在Windows控制台中正确输出字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!