我正在尝试在Clojure中创建一个简单的输入循环。想法是像这样读一行文本:
> look
You see nothing, as this game hasn't actually been written.
我用来尝试此操作的方法如下:
(defn get-input []
(print "> ")
(string/trim-newline (read-line)))
但是,输入循环看起来像这样:
look
> You see nothing, as this game hasn't actually been written.
如何在用户输入之前而不是之后输入角度报价?
答案 0 :(得分:3)
这是一个缓冲问题。 "> "
仅是少量文本,并且不包含换行符(并且由于您未使用println
而不会自动添加换行符),因此它会卡在输出缓冲区中。 flush
之后,您只需要执行print
。
当我在多个地方需要这样的print
/ flush
组合时,通常会创建一个辅助函数来整理内容:
(defn print-fl [& messages]
(apply print messages) ; Pass the strings to print to be printed
(flush)) ; Then flush the buffer manually so small strings don't get stuck
(defn get-input []
(print-fl "> ")
(string/trim-newline (read-line)))
(get-input)
> look
"look"