首页 > 解决方案 > 在 Clojure 中格式化输入提示

问题描述

我正在尝试在 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.

如何在用户输入之前而不是之后打印角度报价?

标签: clojure

解决方案


这是一个缓冲问题。"> "只是少量的文本,并且不包含换行符(并且由于您没有使用,因此不会自动添加换行符println),因此它会卡在 outstream 缓冲区中。你只需要做一个flushafter printing。

当我在多个地方需要这样的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"

推荐阅读