OCaml 一次扫描 2 个值并放入 2 个变量

OCaml scan 2 values at time and put in 2 variables

我有这个代码:

let d = scanf " %d" (fun a->a)
let nrf = read_int()

我想输入2个整数值,然后按回车键。在C语言中我使用scanf("%d %d", &x1, &x2); 但在 OCaml 中,我必须按回车键,然后使用此代码输入第二个值。 有人能告诉我如何在一行中读取两个整数并将它们放入 2 个变量中吗? 感谢您的帮助!

你可以试试这个:

let (c, d) = Scanf.scanf " %d %d" (fun a b -> (a, b))

当你运行这个代码时它看起来像这样:

# let (c, d) = Scanf.scanf " %d %d" (fun a b -> (a, b));;
8 144
val c : int = 8
val d : int = 144
#

第二行是用户(即我)输入的内容。

read_int 需要一个包含 int 的字符串(否则会引发 Failure)。 您必须改用 read_line 从输入中读取字符串和 returns 字符串。 然后,您使用 Jeffrey 提到的 sscanf。