JT1
JT1

Reputation: 453

Reading numbers separated by spaces in OCaml

What is the easiest way to read a bunch of integers from stdin separated by spaces? In this case I know how many there are, although the unknown case corresponding to the while(std::cin >> n) { a.push_back(n); } in C++ would be nice to know too.

Upvotes: 1

Views: 551

Answers (1)

PatJ
PatJ

Reputation: 6144

You can give a try to the Scanf module. See its documentation here.

let get_ints queue =
 let aux () =
  Scanf.scanf "%d " (fun n -> Queue.push n queue); aux ()
 in
 try aux () with _ -> ()

Other standard way allow you to do it, you may want to take a look at ocamllex, Str or Genlex. Of course, there are other lexing/parsing libraries in OCaml but it would be quite a debate as to which one's the best.

Upvotes: 3

Related Questions