Reputation: 1189
I am new to OCaml, and now I am trying to make a simple REPL.
let rec repl () =
print_prompt () ;
let input = Scanf.scanf "%s" (fun x -> x) in
if input = "" then repl ()
else print_endline input
let print_prompt () = print_string "> "
The problem now i am having is: when program starts, it does not display prompt immediately. It waits for my input and prints prompt along with my input.
What I want is:
> "user_input"
"user_input"
But i am getting :
"user_input"
> "user_input"
How can I fix this?
Upvotes: 1
Views: 565
Reputation: 4425
Using readline instead of Scanf :
val read_line : unit -> string
Flush standard output, then read characters from standard input until a newline character is encountered. Return the string of all characters read, without the newline character at the end.
Upvotes: 4
Reputation: 66803
This is almost certainly a buffering problem. In your print_prompt
function, flush the standard output:
flush stdout
Upvotes: 2
Reputation: 35210
Well, you didn't show the print_promt
implementation, but I can guess, that it uses some buffered io function like print_string
or printf
. They print into an intermediate buffer and data will not be displayed unless flush
is called. You can use flush
or flush_all
functions to do this manually. Also you can use a special specificator %!
in printf
formats string:
open Printf
let print_prompt () = printf "> %!"
Upvotes: 2