3
votes

I'm trying to create a simple input loop in Clojure. The idea is to read in a line of text like so:

> look
You see nothing, as this game hasn't actually been written.

The method I'm using to attempt this is below:

(defn get-input []
  (print "> ")
  (string/trim-newline (read-line)))

However, the input loop instead looks like this:

look
> You see nothing, as this game hasn't actually been written.

How would one go about getting the angle quote to print before user input rather than after it?

1

1 Answers

3
votes

This is a buffering issue. "> " is only a small amount of text, and doesn't contain a newline (and one isn't automatically added since you aren't using println), so it gets stuck in the outstream buffer. You just need to do a flush after printing.

When I need a print/flush combo like this in multiple places, I usually create a little helper function to neaten things up:

(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"