Erlang - io:格式的结果/(用io_lib格式化:format / 2)

时间:2012-10-29 20:40:49

标签: erlang

我正在尝试获取io:format / 1的输出结果。

我知道io_lib中有类似的功能,io_lib:format / 2,但输出不同。事实上,它根本没有做任何事情。 如果我尝试绑定io:format,则ok是有界的,并且格式化的字符串会写到控制台。

所以我的问题是,如何使用io_lib得到相同的输出:format / 2? 或者如何将格式化的字符串绑定到变量?

1> A = io:get_line('> ').
> "test".
"\"test\".\n"
2> io:format(A).
"test".
ok
3> B = io_lib:format(A, []).
"\"test\".\n"
4> B.
"\"test\".\n"
5> C = io:format(A).
"test".
ok
6> C.
ok

1 个答案:

答案 0 :(得分:6)

io_lib:format不是io:format的输出函数。相反,io_lib:format仅返回值,但不输出它。

io:format的结果,您认为是“测试”。是发送到终端(包括换行符)的呈现版本,然后返回ok。相反,您看到io_lib:format的{​​{1}}的返回值只是erlang shell对同一字符串的表示,引号和换行符被转义,并被其自己的引号包围。

"\"test\".\n"更常用于将值插入字符串(类似于C的io_lib:format函数)。例如,做一些像

这样的事情
printf

NewString = io_lib:format("The string entered was ~s I hope you like it",[A]) 的值为

NewString

Erlang Shell的代表是:

The string entered was "test".
I hope you like it

如果您只想输出您刚输入的值,那么"The string entered was \"test\".\n I hope you like it" 就足以满足您的需求。