Reputation: 3
I need to ask the user to input an integer and save it in a variable. I can do this with read_int
, but I can't display anything until the user has entered all the inputs I ask him to. Let me explain :
open Format
let ask_for_int name =
printf "%s?\n" name;
let inp = read_int () in
printf "You have entered %d\n" inp; inp
;;
let () = printf "Hello World!\n";
let myVar = ask_for_int "myVar" and myVar2 = ask_for_int "myVar2" in
if myVar = 5 && myVar2 = 10 then printf "Ok\n" else printf "Wrong\n";;
I would like this program to output something like this:
Hello World!
myVar? 5
You have entered 5
myVar2? 10
You have entered 10
Ok
But for now, the only thing I get is
5
10
Hello World!
myVar?
You have entered 5
myVar2?
You have entered 10
Ok
And as long as the user has not entered all the inputs, nothing is displayed on the screen. Does anyone know how to do what I am looking for ?
Thanks
Upvotes: 0
Views: 340
Reputation: 66803
Your partial output is being buffered (hence not displayed until later). You should get what you want if you change the first printf
to this:
printf "%s? %!" name
The %!
specifier asks to flush the output buffer at that point.
To see the other strings you need to flush at those later points also.
However, I wonder why you're using functions from the Format
module. Unless your project has complicated requirements for the format of the output, you would probably be better off using the simpler Printf
module. Since you're just using printf
, the code will be the same. However the Printf
module tries to be more interactive with its buffering. If you change open Format
to open Printf
, your code will work with almost no change (or at least it does for me). You still probably want to change "%s?\n"
to "%s? "
.
Upvotes: 3