制作十六进制16x16数独求解器。我从一个看起来像这样的输入文件开始:
1....c3...5....a
.438.0d5..fab...
.b9..7.f..d.13..
.7...9.e.4....60
4e...f..8.....bc
.6d.9..87..124.f
.2.13....d...5..
..8.6......50.9.
.c.4e......f.2..
..b...4....83.a.
3.172..b4..c.60.
f8.....9..a...cb
7d....f.6.1...e.
..6e.n..2.7..0d.
...984..5c3.ab1.
8....2...0e....3
这些时期代表未知的方块。所以我一直试图用这个程序读入输入文件:
main :-
open('input.txt', read, ID),
repeat,
read(ID, X),
write(X), nl,
X == end_of_file,
close(ID).
每当我运行它时,我都会收到错误:
input.txt:1:1: Syntax error: Operator expected
我相信我遇到了两个我想要帮助的问题。
输入的每一行是否都必须在一段时间内结束,以便能够逐行读取到Prolog中?
您是否也能从包含数字的文件中读入?如果是这样,怎么样?
感谢任何帮助,谢谢!
答案 0 :(得分:3)
dog.
cat.
hello.
如果您使用的是SWI-Prolog,请不要使用4.20 Term reading and writing部分4.19 Primitive character I/O部分,其中包含get_char/2
等谓词因此,解决当前问题的方法是更改
read/2
到
get_char/2
main :-
open('input.txt', read, ID),
repeat,
%read(ID, X),
get_char(ID,X),
write(X), nl,
X== end_of_file,
close(ID).
运行时
?- main.
1
.
.
.
...
.
.
.
3
end_of_file
true ;
ERROR: stream `<stream>(00000000031BB760)' does not exist
ERROR: In:
ERROR: [9] get_char(<stream>(00000000031BB760),_14142)
ERROR: [8] main at c:/...so_question_01.pl:10
ERROR: [7] <user>
因此,这将解决您提出的问题的错误。你现在有一个不同的问题,这是另一个问题,通常在StackOverflow上,你需要提出另一个问题。
因为你不知道你的程序中有第二个错误并且试图找出它可能对刚刚学习Prolog的人有挑战,因为它与回溯有关,这里是快速修复。
main :-
open('input.txt', read, ID),
repeat,
%read(ID, X),
get_char(ID,X),
write(X), nl,
X == end_of_file, !, % Notice the cut (!) at the end of this line
close(ID).
运行时
?- main.
1
.
.
.
...
.
.
.
3
end_of_file
true.