开发者

swi prolog , how to read the data for the txt.file

Can someone help me with my file reading predicate?

get_userinfo: write('\nEnter Name:'),
          readln(Name),
          write('\nEnter Gender:'),
          read(Gender),
          append('marriage.txt') ,
         开发者_运维百科 write(personal(Name,Gender,Age,Attr)),nl,
          told.

This is my text file:

personal(chong,male).
personal(jack,female).
personal(kk,male).


Not sure where the problem is: reading or writing? It looks like you have the code you need. I rewrote it to separate things out a little more and came up with this:

get_userinfo(personal(Name, Gender, Age, Attr)) :-
      write('Enter name: '),
      readln([Name|_]),
      write('Enter gender: '),
      readln([Gender|_]),
      write('Enter age: '),
      readln([Age|_]),
      write('Enter attr: '),
      readln([Attr|_]).

record_userinfo(Filename, Person) :-
      append(Filename),
      write(Person), nl,
      told.

From here you can use it like so:

:- get_userinfo(Person), record_userinfo('marriage.txt', Person).

If you're trying to read this in, you should probably just consult it: [marriages] but you'll need to rename it to end in '.pl'.

Edit: more information about reading files.

In Prolog, there's reading and there's consulting. Reading is as in other languages, you manually read in data from the file and process it. Consulting is something you can use in cases where your input file is also Prolog; it amounts to parsing the file and adding the facts and predicates defined in it to the currently active session. For example, to consult the marriage.txt file, you would use this:

:- ['marriage.txt'].

Now that you've consulted it, you can perform queries with the new facts in the database:

?- ['marriages.txt'].
% marriages.txt compiled 0.00 sec, 1,328 bytes
true.

?- personal(X, Gender).
X = chong,
Gender = male ;
X = jack,
Gender = female ;
X = kk,
Gender = male.

?- personal(X, male).
X = chong ;
X = kk.

?- personal(chong, X).
X = male.

If you want to get a list of all the personal/2 facts, you can do something like this:

?- setof(personal(X,Y), personal(X,Y), Qs).
Qs = [personal(chong, male), personal(jack, female), personal(kk, male)].
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜