Print_string not flushing?

I’m trying to collect user input by use of the following function:

let promptString ?(msg=None) s =
  let prompt = match msg with
    | Some msg -> msg
    | None     -> String.capitalize_ascii s
  print_string @@ prompt ^ ": ";
  flush stdout;
  let value = read_line () in
  Val (s, String value)

However, when running the program, the prompt never gets printed before attempting to read a line. I call this function 3 times, and it accepts 3 line inputs before finally flushing the prompt text. Any idea how to fix this?

1 Like

On Ubuntu Linux with ocaml 4.10.0, I ran your code (with minor change to remove “Val”):

# promptString ~msg:(Some "f") "a" ;;
f: zzzz;;
- : string * string = ("a", "zzzz;;")

Perhaps you have an environmental problem?

Maybe try this:

Printf.print "%s\n%!" your_string

Same problem here. Neither print_string "a" nor Printf.printf "a%!" print anything (even when followed by flush stdout). I have to use print_endline "a" and then it works.
In case this is relevant, this comes in

let test x =
    Seq.iter (f x) 0
  with _ -> Printf.printf "There was an error (raised by f).%!"

I guess this comes from the delayed evaluation of Seq, but it’s strange that %! has no effect.

I don’t think your program typechecks: the second argument to Seq.iter is supposed to be a Seq.t, i.e. a unit -> Seq.node, not an int.

In case this is relevant: in some terminals / using some prompts, the last line of command output does not appear unless it ends with a newline. For example, on my computer: