Reading numbers from standard input is a combination of reading strings and parsing such strings as numbers.
The parse
function is used to parse a string into the desired number type:
julia> parse(Int, "17")
17
julia> parse(Float32, "-3e6")
-3.0f6
The format expected by parse(T, x)
is similar to, but not exactly the same, as the format Julia expects from number literals:
julia> -00000023
-23
julia> parse(Int, "-00000023")
-23
julia> 0x23 |> Int
35
julia> parse(Int, "0x23")
35
julia> 1_000_000
1000000
julia> parse(Int, "1_000_000")
ERROR: ArgumentError: invalid base 10 digit '_' in "1_000_000"
in tryparse_internal(::Type{Int64}, ::String, ::Int64, ::Int64, ::Int64, ::Bool) at ./parse.jl:88
in parse(::Type{Int64}, ::String) at ./parse.jl:152
Combining the parse
and readline
functions allows us to read a single number from a line:
function asknumber()
print("Enter a number: ")
parse(Float64, readline())
end
which works as expected:
julia> asknumber()
Enter a number: 78.3
78.3
The usual caveats about floating-point precision apply. Note that parse
can be used with BigInt
and BigFloat
to remove or minimize loss of precision.
Sometimes, it is useful to read more than one number from the same line. Typically, the line can be split with whitespace:
function askints()
print("Enter some integers, separated by spaces: ")
[parse(Int, x) for x in split(readline())]
end
which can be used as follows:
julia> askints()
Enter some integers, separated by spaces: 1 2 3 4
4-element Array{Int64,1}:
1
2
3
4