how can i put user input in a array in julia

Viewed 51

I would like to collect user input (a list of number separated by a space) split it in to an array and transform the data in it from string to float. Basically i want to recreate this python code in Julia:

userlist = input('[+]type in a list of number separated by a space: ').split()
for i in range(len(userlist)): userlist[i] = float(userlist[i])

i tried this but didn't work:

print("type in a list of number separated by a space: ")
userinput = readline()
userlist = rsplit(userinput, " ")
for i in 0:length(userlist)
  userlist[i] = userlist[i]::Float64
end
2 Answers

You're close. You parse a String into Float64 with parse, not a type assertion.

userlist[i] = parse(Float64, userlist[i])

This still won't quite work, since userlist is an array of strings and can't store floats (arrays in Julia are stored with their type by default, for efficiency). You could make a new array and then do the for loop like you have been, but you can also just use map.

userlist = map(x -> parse(Float64, x), userlist)

I would recommend using DelimitedFiles as it is usually more robust (you always end up with user inputting some wrong data etc.:

readdlm(IOBuffer(readline()))

For an example:

julia> readdlm(IOBuffer(readline()))
1 2 3
1×3 Matrix{Float64}:
 1.0  2.0  3.0
Related