douxing9641 2012-08-21 10:41
浏览 116
已采纳

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

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).

How would you make sure the go exe print correctly encoded strings for a console windows, ie print for instance:

éèïöîôùòèìë

instead of (without any translation to the right charset)

├®├¿├»├Â├«├┤├╣├▓├¿├¼├½
  • 写回答

4条回答 默认 最新

  • dongsonghen9931 2017-07-08 20:29
    关注

    Since 2016, You can now (2017) consider the golang.org/x/text, which comes with a encoding charmap including the ISO-8859 family as well as the Windows 1252 character set.

    See "Go Quickly - Converting Character Encodings In Golang"

    r := charmap.ISO8859_1.NewDecoder().Reader(f)
    io.Copy(out, r)
    

    That is an extract of an example opening a ISO-8859-1 source text (my_isotext.txt), creating a destination file (my_utf.txt), and copying the first to the second.
    But to decode from ISO-8859-1 to UTF-8, we wrap the original file reader (f) with a decoder.

    I just tested (pseudo-code for illustration):

    package main
    
    import (
        "fmt"
    
        "golang.org/x/text/encoding"
        "golang.org/x/text/encoding/charmap"
    )
    
    func main() {
        t := "string composed of character in cp 850"
        d := charmap.CodePage850.NewDecoder()
        st, err := d.String(t)
        if err != nil {
            panic(err)
        }
        fmt.Println(st)
    }
    

    The result is a string readable in a Windows CMD.
    See more in this Nov. 2018 reddit thread.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料