【问题标题】:Reading from an input file that has lines with no periods at the end (and numbers)从末尾没有句点的行(和数字)的输入文件中读取
【发布时间】:2018-03-20 23:06:38
【问题描述】:

制作十六进制 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

我相信我遇到了两个需要帮助的问题。

  1. 输入的每一行是否都必须以句点结尾才能逐行读入 Prolog?

  2. 您是否也可以从包含数字的文件中读取?如果有,怎么做?

不胜感激,谢谢!

【问题讨论】:

    标签: file input prolog


    【解决方案1】:

    您的错误是因为read/2 读取为terms,例如

    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.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      • 1970-01-01
      • 2011-08-07
      • 1970-01-01
      • 2018-10-04
      • 2017-05-24
      相关资源
      最近更新 更多