Reputation: 351
I'm using Julia.
When parsing a string to Int,
parse.(Int,split(readline()))
works
(e.g. input:""123 456""
→ output:[123,456]
),
but parse.(Int,split(readlines()))
doesn't. How should I do?
I know each parse.(Int,split(readlines()[i]))
passes, but I want to parse at one try something like parse.(Int,split(readlines()))
.
Upvotes: 3
Views: 366
Reputation: 14695
The easiest way would be to use the DelimitedFiles
package from the Julia standard library:
julia> readdlm(stdin, Int)
1 23 4
6 83 23
2×3 Matrix{Int64}:
1 23 4
6 83 23
(the second and third lines are user input by me.)
If you're reading from a file (readline("myfile.txt")
in the original code), you can pass the filename instead of stdin
(readdlm("myfile.txt", Int)
).
Upvotes: 2
Reputation: 42214
Perhaps the nicest way would be by using DelimitedFiles
such as:
julia> open("f.txt", "w") do f; println(f,"1 2 3\n4 5 6"); end
julia> using DelimitedFiles
julia> readdlm("f.txt",Int)
2×3 Matrix{Int64}:
1 2 3
4 5 6
Something more similar to your code could look like this:
julia> map(row -> parse.(Int,row), split.(readlines("f.txt")))
2-element Vector{Vector{Int64}}:
[1, 2, 3]
[4, 5, 6]
Upvotes: 2