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

G41*_*143 2 ocaml ocaml-lwt

你如何正确使用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
    )
Run Code Online (Sandbox Code Playgroud)

我在提示时编译,运行并输入了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"
        )
    )
Run Code Online (Sandbox Code Playgroud)

我想我应该发布一些代码来演示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
    )
Run Code Online (Sandbox Code Playgroud)

Éti*_*lon 6

这将读取二进制编码的整数,例如,以便从文件中反序列化某些数据.

您阅读的是十六进制0x34333231的875770417,它依次对应于小端排序中的'1','2','3'和'4'的ASCII编码.

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