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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!