Assign and print an input string to a variable. Lisp

2.5k views Asked by At

I want my program to ask for an expression, assign an inputted string to a variable 'exp' and then print the expression.

However I am having some trouble. I first tried using (read)

(princ "Enter a expression to be evaluated.")
(setf exp (read))
(princ exp)

However when i use this code, this happens.

Hello this is an expression            ;This is what I input
Enter a expression to be evaluated.HELLO
T

I then tried to use (read-line), but when I do this, I don't seem to be asked for an input at all.

(princ "Enter a expression to be evaluated.")
(setf exp (read-line))
(princ exp)

gets

Enter a expression to be evaluated.
T

The program just ends.

After some answers I have come up with this

(defun get-input (prompt)
  (clear-input)                     
  (write-string prompt)             
  (finish-output)                   
  (setf exp (read-line)))           

(get-input "Enter an expression: ")
(princ exp)

However when i run this the following happens

My first sentence                            ;My first input
Enter an expression: My second sentence      ;it then asks for input, i do so
My second sentence                           ;my second input is printed back at me
T
1

There are 1 answers

7
Rainer Joswig On

This is kind of a FAQ.

Output can be buffered. Use FINISH-OUTPUT to make sure that the output has actually reached its destination.

READ reads Lisp s-expressions. It returns the corresponding data-structure. It's only useful when you enter a valid s-expression.

READ-LINE reads a line and returns a string.

Example:

* 
(defun ask (&optional (message "Input: "))
  (clear-input)           ; get rid of pending input
  (write-string message)  ;
  (finish-output)         ; make sure output gets visible
  (read-line))            ; read a line as a string

ASK
* (ask "Name: ")
Name: Rainer

"Rainer"
NIL

File p.lisp:

(defun get-input (prompt)
  (clear-input)
  (write-string prompt)
  (finish-output)
  (read-line))

(write-string (get-input "Enter a sentence: "))
(finish-output)

Output

* (load "/tmp/p.lisp")
Enter a sentence: foo is not a bar
foo is not a bar
T