0

我试图退出循环,将文件内容读入列表,当我点击“停止”的文本行时。这是我的代码:

let f_in = "file.text"
let lines = ref [];;

  let chan = open_in f_in in
  try
    while true do

      let line = input_line chan in
      if line = "stop" then raise End_of_file;
      lines := input_line chan :: !lines

    done
  with End_of_file -> close_in chan

问题是它正在读取额外的 1 行,并且它不会读取文本中包含“停止”一词的行。一个例子是这种文件:

aaa
bbb stop
ccc stop
ddd
eee
stop
fff

现在我的代码应该打印所有这些行,并在仅包含“停止”一词的行处停止阅读。有人可以解决这个问题吗?谢谢。

4

1 回答 1

0

将第二个替换为input_lineline想要的结果。

let f_in = "file.text"
let lines = ref [];;

let chan = open_in f_in in
  try
    while true do

      let line = input_line chan in
      if line = "stop" then raise End_of_file;
      lines := !lines @ [ line ]

    done
  with End_of_file -> close_in can

存储的结果lines是:

["aaa"; "bbb stop"; "ccc stop"; "ddd"; "eee"]
于 2013-04-09T01:39:39.897 回答