F #: printf vs Console.WriteLine

I play in the f # interactive window and find that printf is not working as I expected. In the following snippet ReadLine runs before the first printf

let run () = printf "What is your name?" Console.Out.Flush() let value = System.Console.ReadLine() printf "Hello, %s, nice to meet you!" value run() 

If I change printf to Console.WriteLine, it works as expected.

 let run () = Console.Out.WriteLine "What is your name?" Console.Out.Flush() let value = System.Console.ReadLine() printf "Hello, %s, nice to meet you!" value run() 

What happens with printf? Is there a flush call that I can print before reading? Is there a f # read line I should use?

----------------- [Change] --------------------

After reading the answer of Fedor Soikin, I tried to check the following. Of course, what was printed on the screen was Hello , and after entering some input, it printed World .

 open System let run () = printf "Hello\n World" let value = System.Console.ReadLine() let msg = sprintf "Hello, %s, nice to meet you!" value printf "%s" msg run() 
+5
source share
1 answer

printf equivalent to Console.Write , and printfn equivalent to Console.WriteLine . You are comparing functions that are not equivalent.

Just replace printf with printfn and your example will work as expected.


Why this does not work with printf and Console.Write
This is just an FSI way: it does not print text in the output window until your program creates a new line. There is some good motivation for this: if the FSI immediately prints the text, it can break your output with its own output of some intermediate information.

Calling Console.Flush has nothing to do with it. When your program runs in FSI, you actually do not have direct access to the console; it goes through its own FSI filter. FSI immediately receives your input (i.e. there is no need to call Flush ), it just does not print it right away (see above).

If you run your program yourself, and not in FSI, then your output will be displayed as you expect.

+7
source

All Articles