OCaml - How do I convert string to int?

时间:2016-10-20 12:43:52

标签: string int ocaml

Im' newbie in Ocaml and Im'trying to do this :

let medio a b =
    (a + b);;
let () = Printf.printf "%d + %d  = %d\n" Sys.argv.(1) Sys.argv.(2) (medio Sys.argv.(1) Sys.argv.(2))    

Sys.argv.(1) has to be the arg[1] ~ in C

Now I want to use them like parameters for my function medio, but they 're strings. How can I parase them into int ? Is there a ocaml function to do it? In python is int(Sys.argv.(2)) or int atoi(const char *str) in C in ocaml ?

3 个答案:

答案 0 :(得分:6)

You could use the 'int_of_string' function described in the documentation.

答案 1 :(得分:4)

I would start with int_of_string. Generally, OCaml standard library provides functions, that converts between types, of the following form <output>_of_<input>, e.g., float_of_string, string_of_int, etc.

答案 2 :(得分:0)

您可以使用Arg模块解析命令行参数。

示例:test.ml

  let ri_a=ref 0 in
  let ri_b=ref 0 in

  Arg.parse [
    ("-a",Arg.Int      (function i -> ri_a:=i),"");
    ("-b",Arg.Int      (function i -> ri_b:=i),"");
    ] (function s -> ()) "ERROR";

  Printf.printf "%d %d" !ri_a !ri_b;

使用它

./test -a 2 -b 3
2 3