最近,我开始研究OCaml。作为结果程序执行,我发现了一个奇怪的事情。示例是TicTacToe控制台游戏的一部分。 这段代码:
let move pl arr =
let () = Printf.printf "Player %i, enter two numbers: \n" pl in
let x1 = Scanf.scanf "%i\n" (fun n -> n) in
let y1 = Scanf.scanf "%i\n" (fun n -> n) in
if (pl=1) then Array.set arr.(x1) y1 "X"
else Array.set arr.(x1) y1 "O"
;;
给出如此奇怪的结果:
root@genesis:/home/kirill/workspace/Test2# corebuild hw.native
Finished, 4 targets (0 cached) in 00:00:00.
root@genesis:/home/kirill/workspace/Test2# ./hw.native
1
1
Player 1, enter two numbers:
root@genesis:/home/kirill/workspace/Test2#
为什么这段代码:
let x1 = Scanf.scanf "%i\n" (fun n -> n) in
let y1 = Scanf.scanf "%i\n" (fun n -> n) in
在此代码之前运行:
let () = Printf.printf "Player %i, enter two numbers: \n" pl in
???
抱歉英语不好。谢谢你的回答!
答案 0 :(得分:2)
在所有语言中缓冲IO库而不是直接输出到设备中,将首先输出到中间缓冲区。一旦缓冲区满或溢出,它们将刷新数据。他们还将在您的程序退出时刷新数据。这里,在程序完成之前,数据不会被刷新(因此不会被打印)。您可以使用flush
或flush_all
函数,或使用OCaml特定的printf说明符%!
来刷新特定程序点的数据,例如
Printf.printf "Player %i, enter two numbers: \n%!"