Console input giving spurious values
-
15-06-2021 - |
Pregunta
After trying this simple console input with 5, the result is shown as 53
printfn "Enter no. of blocks: "
let nBlock = System.Console.Read()
printfn "entered value is %O" nBlock
Tried it on the interactive, still getting wrong results. Any solutions please?
Solución
You should try something like:
printfn "Enter no. of blocks: "
let nBlock = System.Console.ReadLine() |> System.Int32.Parse
printfn "entered value is %d" nBlock
Explanation:
you code only reads one character - as Lee mentioned with this you will read a line (ending after you press return) and parse that string into a int.
Remark: maybe you will want to check for a number, you can do this with TryParse:
printfn "Enter no. of blocks: "
let nBlock =
match System.Console.ReadLine() |> System.Int32.TryParse with
| true, n -> n
| false, _ -> -1
printfn "entered value is %d" nBlock
Of course you will have to check for the error case (-1) or change it into a option or something.
Otros consejos
System.Console.Read()
returns an int
, therefore nBlock
contains the int representation of the input character '5', which is 53. You can convert it back to a char
using Convert.ToChar
. Since each character is returned individually, you will need wrapping it into a loop to process the entire input, as described in this article.
A better approach is probably to use Console.ReadLine()
to read then entire line and parse that to an int
.