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

报告相同问题?

悬赏问题

  • ¥15 有偿求码,CNN+LSTM实现单通道脑电信号EEG的睡眠分期评估
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路