2011-02-24 85 views
8

我們怎樣才能從用戶在序言東西: 例如:用戶輸入,我們該怎麼做?

animal(dog). 
animal(cat). 
write('please type animal name:'),nl. 
/* How to read from user and store it to X 
and then check that user has typed animal name ?*/ 
?-animal(X). 

回答

14

您可以使用read了點。例如,你可以寫read(X), animal(X).到序言解釋或寫入到一個腳本文件這樣的:

:- read(X), animal(X). 

如果你再輸入一個有效的動物名進入提示,它將如果你輸入一個無效的名稱勢必X. ,它不會。

或者你可以定義這樣一個過程:

read_animal(X) :- 
    write('please type animal name:'), 
    nl, 
    read(X), 
    animal(X). 

然後像read_animal(X).解釋調用它的。

請注意,輸入需要以.結尾。

+0

動物(狗)。 動物(貓)。 動物(牛)。 寫('請輸入動物名稱:'),nl。 閱讀(X)。 動物(X)。 – 2011-02-24 17:02:53

+0

根本不工作 – 2011-02-24 17:03:10

+3

@Parkhid:它是'read',而不是'Read'。還要注意,你需要用'.'來終止輸入。我編輯了我的答案來澄清。它絕對有用。 – sepp2k 2011-02-24 17:16:02

-1

動物('X')。 輸入: - write(「輸入你的名字」),nl, read(X),nl, write(X)。

-1

閱讀值 %name id stud_name('ankit',01)。 stud_name('varun',02)。

Read_stud: - 寫( 「寫名字就知道了學生的ID」),NL, 讀(輸入),NL, stud_name(輸入,輸出),NL, 寫(輸出)。

+0

Hello ankit!歡迎來到Stack Overflow。如果你想知道爲什麼你的答案被低估了,這裏有一些提示:(a)這個問題已經六年了。 (b)已經有許多贊成的答案,你的回答沒有增加任何新東西。 (c)請解釋您用完整句子發佈的代碼。 (d)請格式化您的代碼並使用正確的代碼格式(https://stackoverflow.com/help/formatting)。 – 2017-05-25 16:23:14