Reading a string (from a file) in Prolog

橙三吉。 提交于 2019-12-05 21:13:19

You can use read_line_to_codes/2 or read_line_to_codes/3. An example program which reads individual lines from stdin and prints them to stdout is the following:

read_lines([H|T]) :-
  read_line_to_codes(user_input, H), H \= end_of_file, read_lines(T).
read_lines([]).

write_lines([]).
write_lines([H|T]) :-
  writef("%s\n", [H]), write_lines(T).

main :-
  read_lines(X), write_lines(X).

(This uses writef/2 for printing.) There are also read_stream_to_codes/2 and read_stream_to_codes/3, which are not concerned with lines. The following code prints all input from stdin in one go to stdout:

main :-
  read_stream_to_codes(user_input, X), writef("%s", [X]).

Of course it's also possible to read from a file instead of stdin. For more, see the readutil library.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!