试图打印Unicode字符时运行时异常 [英] Run-time exception when attempting to print a Unicode character

查看:154
本文介绍了试图打印Unicode字符时运行时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Char 是Haskell中Unicode字符的类型,而 String 仅仅是 [ Char] (即 Char 项目列表)。这里有一些简单的代码:

  main = putStrLn© -  Unicode字符串

这段代码编译得很好,但是当我在 PowerShel.exe cmd.exe


app.exe::commitBuffer:无效参数(无效字符)

为什么会发生这种情况?奇怪的是,当我在C#中做同样的事情时,我没有任何例外:

  Console.WriteLine(©); 

在.NET中,字符也是Unicode。 PowerShell cmd 打印 c ,而不是©,但是至少我不会例外。我怎么才能让我的Haskell可执行文件顺利运行?

解决方案

我认为这应该算作GHC中的一个bug,解决方法。 GHC程序中的所有句柄的默认编码(二进制模式下打开的除外)只是控制台接受的编码,没有错误处理。幸运的是,您可以添加像这样的错误处理。

  makeSafe h = do 
ce'< - hGetEncoding h
case ce'
Nothing - > return()
Just ce - > mkTextEncoding((takeWhile(/ ='/')$ show ce)++// TRANSLIT)>> =
hSetEncoding h

main = do
mapM_ makeSafe [stdout,stdin,stderr]
- 您的主函数的其余部分。


Char is the type for Unicode characters in Haskell, and String is simply [Char] (i.e. a list of Char items). Here is some simple code:

main = putStrLn "©" -- Unicode string

This code compiles fine, but I get the runtime exception when I run it in the PowerShel.exe or cmd.exe:

app.exe: : commitBuffer: invalid argument (invalid character)

Why does this happen? Weirdly enough, when I do the same in C#, I get no exception:

Console.WriteLine("©");

In .NET, chars are Unicode too. PowerShell or cmd prints c instead ©, but at least I get not exception. How can I get my Haskell executable to run smoothly?

解决方案

I think this should count as a bug in GHC, but there is a workaround. The default encoding for all handles in a GHC program (except those opened in Binary mode) is just the encoding accepted by the console with no error handling. Fortunately you can add error handling with something like this.

makeSafe h = do
  ce' <- hGetEncoding h
  case ce' of
    Nothing -> return ()
    Just ce -> mkTextEncoding ((takeWhile (/= '/') $ show ce) ++ "//TRANSLIT") >>=
      hSetEncoding h

main = do
  mapM_ makeSafe [stdout, stdin, stderr]
  -- The rest of your main function.

这篇关于试图打印Unicode字符时运行时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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