如何在DOS窗口中正确输出字符串? [英] How to properly output a string in a DOS window with go?

查看:631
本文介绍了如何在DOS窗口中正确输出字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在go中有一个 exe ,用于打印 utf-8 编码

由于该exe是从DOS窗口使用,其输出被压缩,因为DOS使用 ibm850 编码(又名 代码页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 DOS windows, its output is mangled because DOS uses ibm850 encoding (aka code page 850).

如何确保 exe 为DOS窗口打印正确编码的字符串,例如打印:

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

éèïöîôùòèìë

(没有任何翻译到右侧字符集

instead of (without any translation to the right charset)

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


推荐答案

在线书使用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.

这里是一个解决方案(我可能错过了一个更简单的一个),使用 library 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:

éèïöîôùòèìë

翻译功能详述如下:

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

这篇关于如何在DOS窗口中正确输出字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆