2
votes

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

3 Answers

10
votes

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

4
votes

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.

0
votes

You can use Arg module for parsing command line arguments.

Example: 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;

To use it

./test -a 2 -b 3
2 3