gpt4 book ai didi

ocaml - Lwt_io.read_int 的正确用法是什么?

转载 作者:行者123 更新时间:2023-12-02 07:21:45 25 4
gpt4 key购买 nike

如何正确使用Lwt_io.read_int?我尝试了我认为明显的用法,但没有得到明显的结果...

open Lwt.Infix

let _ =
Lwt_main.run
(
Lwt_io.print "Enter number: " >>=
fun () -> Lwt_io.read_int (Lwt_io.stdin) >>=
fun d -> Lwt_io.printf "%d\n" d
)

我编译运行,提示输入12345,程序显示875770417。

我在这里遗漏了一些东西......

在下面的帮助下,我得到了这个。它有效,我希望它是正确的。

open Lwt.Infix

let _ =
Lwt_main.run
(
Lwt_io.print "Enter number: " >>=
fun () -> Lwt_io.read_line (Lwt_io.stdin) >>=
fun s ->
(
try
Lwt.return_some( Pervasives.int_of_string s)
with
| _ -> Lwt.return_none
) >>=
fun o ->
Lwt_io.print
(
match o with
| Some i -> Printf.sprintf "%d\n" i
| None -> "Ooops, invalid format!\n"
)
)

我想我应该发布一些代码来演示 Lwt_io.read_int 的正确用法。

open Lwt.Infix
open Lwt_io

let _ =
Lwt_main.run
(
let i, o = Lwt_io.pipe() in
Lwt_io.write_int o 1 >>=
fun () -> Lwt_io.flush o >>=
fun () -> Lwt_io.close o >>=
fun () -> Lwt_io.read_int i >>=
fun d -> Lwt_io.printf "%d\n" d >>=
fun () -> Lwt_io.close i
)

最佳答案

这会读取一个二进制编码的整数,例如为了反序列化文件中的一些数据。

您读到的 875770417 是十六进制的 0x34333231,它依次对应于小端顺序中的“1”、“2”、“3”和“4”的 ASCII 编码。

您可能想使用 Lwt_io.read_line 读取字符串并使用 int_of_string 转换结果。

关于ocaml - Lwt_io.read_int 的正确用法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44067361/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com