【问题标题】:printing a special character in Erlang在 Erlang 中打印特殊字符
【发布时间】:2021-01-15 02:57:12
【问题描述】:

我是Erlang的新手,我想知道有没有办法在没有' '的情况下将#这样的特殊字符打印到输出中,我想打印#,相关代码是:

case {a(N),b(N)} of
    {false,_} -> {false,'#'};

但输出看起来像:{false,'#'},有没有办法得到# 而不是'#'

【问题讨论】:

    标签: erlang


    【解决方案1】:

    在 Erlang 中,单引号用于表示原子。所以'#' 变成了一个原子而不是特殊字符。

    您可能需要考虑使用 $# 的值,它表示 # 字符或“#”表示字符串(字符串是 Erlang 中的字符列表)。

    在这种情况下,{false, $#} 将产生{false, 35}(Ascii 值为 $#)。 如果要打印字符,则需要使用io:format

    1> io:format("~c~n",[$#]).
    #
    ok
    

    如果你使用字符串(字符列表),那么:

    2> io:format("~s~n",["#"]).
    #
    ok
    

    其中 ok 是 io:format 的返回值。

    【讨论】:

      【解决方案2】:

      在您给出的示例中,您不打印任何内容,您所显示的是shell 将自动输出的内容:最后一条语句的结果。如果你想打印给定格式的东西,你必须调用一个 io 函数:

      1> io:format("~p~n",["#"]). % the pretty print format will show you are printing a string
      "#"
      ok
      2> io:format("~s~n",["#"]). % the string format is used to print strings as text
      #
      ok
      3> io:format("~c~n",[$#]). % the character format is used to print a charater as text 
      #
      ok
      4> io:format("~p~n",[{{false,$#}}]). % note that a character is an integer in erlang.
      {{false,35}}
      ok
      5> io:format("~p~n",[{{false,'#'}}]). % '#' is an atom, not an integer, it cannot be print as # without '
                                            % because it doesn't start by a lower case character, and also
                                            % because # has a special meaning in erlang syntax
      {{false,'#'}}
      ok
      6> io:format("~p~n",[{{false,'a#'}}]).
      {{false,'a#'}}
      ok
      7> io:format("~p~n",[{{false,'ab'}}]).
      {{false,ab}}
      ok
      8> io:format("~p~n",[{{false,a#}}]).  
      * 1: syntax error before: '}'
      8>
      

      注意每次shell打印最后一条语句的结果:io:format/2返回ok

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-27
        • 2015-11-30
        • 1970-01-01
        • 2014-08-13
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        相关资源
        最近更新 更多