How to read user input using f# interactive in visual studio?

15,302

Solution 1

The F# Interactive console in Visual Studio does not support reading input, so there is no way to ask for an input from the console. If you're running code interactively, you can always enter the input in the editor, so the best workaround is to have let binding at the beginning where you enter the input before running your code. You can use #if to support both scenarios:

#if INTERACTIVE
// TODO: Enter input here when running in F# Interactive
let input = "42"
#endif

try 
    #if INTERACTIVE
    Some(int32 input)
    #else
    let x = System.Console.ReadLine(); 
    Some(int32(x)) 
    #endif
with 
    | :? System.FormatException -> 
        printfn "Invalid number!" 
        Some(0) 

Solution 2

Try below, it works fine on my machine (VS 2013, F# 3.1 12.0.21005.1)

let inputTest i = 
    printfn "iter - %d" i
    let input = System.Console.ReadLine()
    printfn "%s" input
    System.Console.ReadLine() |> ignore

List.iter inputTest [1..3]

Solution 3

If you open F# interactive as its own process (by directly running fsi.exe, the code works fine - here is what happened to me:

> printfn "Enter a number:"
- let r =
-     try
-        let x = System.Console.ReadLine();
-        Some(int32(x))
-     with
-        | :? System.FormatException -> printfn "Invalid number!"
-                                       Some(0)
- ;;
Enter a number:
5

val r : int32 option = Some 5
Share:
15,302
Toadums
Author by

Toadums

Updated on June 04, 2022

Comments

  • Toadums
    Toadums almost 2 years

    So I am trying to do something simple:

     printfn "Enter a number:"
        try
           let x = System.Console.ReadLine();
           Some(int32(x))
        with
           | :? System.FormatException -> printfn "Invalid number!"
                                          Some(0)
    

    I want to print the message, then get the user to input a number, and try to convert it to an int and return it.

    If I just compile the code (by typing fsc a3.fs on the command line), it works fine. It pauses, waits for input, then returns Some(int).

    If I copy and paste the code into the FSI on the command line, it works great.

    But when I am in visual studio, and I run the code in the FSI (highlight + alt+enter), it just goes right over the input part and the exception is thrown (and caught).

    Here is the output when I run in the FSI (in visual studio):

    Enter a number:
    Invalid number!
    0
    

    As you can see, It doesnt ever actually pause and wait for me to enter input.

    Anyone know how to make this work?

    Thanks!