遵循 WITH-OUTPUT-TO-STRING 的文档和 GET-OUTPUT-STREAM-STRING ,我希望以下方法有效,而且它们确实有效:
(print
(with-output-to-string (sb nil)
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
sb))
(print
(let ((sb (make-string-output-stream)))
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
(get-output-stream-string sb)))
但是,下面的例子接近于其中一个例子 WITH-OUTPUT-TO-STRING , 不:
(print
(with-output-to-string (sb (make-array
'(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t))
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
sb))
相反,生成输出流本身,而不是其中包含的字符串:
#<SB-IMPL::FILL-POINTER-OUTPUT-STREAM {1005FBE523}>
我一直无法找到一种方法来提取输出中的字符串 溪流。我怀疑这与动态范围有关,但我的 理解步履蹒跚,在这里。
显然,我有办法达到预期的效果,所以我只是 很想发现我对这门语言的误解。
因为文档说结果未定义 GET-OUTPUT-STREAM-STRING 在由 MAKE-STRING-OUTPUT-STREAM 创建的流上不是,我 以下内容不起作用并不奇怪:
(print
(with-output-to-string (sb (make-array
'(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t))
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
(get-output-stream-string sb)))
但我仍然很感激能在我的第三个文件中找到一种提取字符串的方法 示例。
最佳答案
请注意 WITH-OUTPUT-TO-STRING以两种不同的方式返回值:
- 如果您没有给它任何字符串或
NIL
,那么它会创建一个字符串并返回它。 - 如果你给它一个字符串,那么它返回最后一个主体形式的结果值。
您的代码:
(print
(with-output-to-string (sb (make-array ; creates a string
'(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t))
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
sb) ; you return the stream (which makes not much sense), but not the string
)
您已通过调用 MAKE-ARRAY
创建了一个字符串。就在那里。用它。为此,您通常需要将其绑定(bind)到某个变量。
返回字符串的例子:
(let ((s (make-array '(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t)))
(with-output-to-string (sb s)
(format sb "~A " "hello, ")
(format sb "~A~&" "world"))
s)
或
(let ((s (make-array '(0)
:element-type 'base-char
:fill-pointer 0
:adjustable t)))
(with-output-to-string (sb s)
(format sb "~A " "hello, ")
(format sb "~A~&" "world")
s))
在最后一种情况下,with-output-to-string
返回值,因为它得到了一个用作输出目标的字符串。
关于common-lisp - 惊喜打印到字符串(普通的 lisp),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35964160/