将输入字符串分配并打印到变量。口齿不清

时间:2014-11-29 15:29:46

标签: input lisp common-lisp sbcl buffered

我希望我的程序要求表达式,将输入的字符串分配给变量'exp'然后打印表达式。

但是我遇到了一些麻烦。我首先尝试使用(阅读)

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

然而,当我使用此代码时,会发生这种情况。

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

然后我尝试使用(read-line),但是当我这样做时,似乎根本没有要求输入。

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

Enter a expression to be evaluated.
T

该计划刚刚结束。

经过一些回答后,我想出了这个

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

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

然而,当我运行时,会发生以下情况

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 个答案:

答案 0 :(得分:4)

这是一种常见问题解答。

可以缓冲输出。使用FINISH-OUTPUT确保输出实际到达目的地。

READ读取Lisp s表达式。它返回相应的数据结构。它只在输入有效的s表达式时才有用。

READ-LINE读取一行并返回一个字符串。

示例:

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

档案p.lisp

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

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

输出

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