Reputation: 87
I have a text file like this:
5
10
5 3 2 7 4
2 8 4 2 5
I need to put the first two numbers in to different varibles as integers, I SUCCESSFULLY did that with:
arq = open("C:\\Users\\Breno Maia\\Desktop\\test.txt", "r")
n = readline(arq)
c = readline(arq)
n=parse(Int64, n)
c=parse(Int64, c)
Now, I need to put the third and forth lines in two different arrays of integers. My solution that DOESN'T work is:
line3=readline(arq)
line4 = readline(arq)
p= split(line3, "") //convert string into array
deleteat!(p, findall(x->x==" ", p)) //remove spaces
for i in p
i=parse(Int64, i)
end
When I print line3, it shows: "SubString{String}["5", "3", "2", "7", "4"]" plz help. Thank you
Upvotes: 3
Views: 569
Reputation: 42214
I recommend using readdlm
to simplify tasks such as this.
The first two values can be get in one line, e.g.:
v1,v2=filter(x->typeof(x)<:Int, permutedims(readdlm("test.txt"))[:])
Here is the full code that gets first value, second value, third and fourth line:
shell> more test.txt
5
10
5 3 2 7 4
2 8 4 2 5
julia> using DelimitedFiles
julia> dat = readdlm("file.txt")
4×5 Array{Any,2}:
5 "" "" "" ""
10 "" "" "" ""
5 3 2 7 4
2 8 4 2 5
julia> dat[1,1], dat[2,1], Int.(dat[3,:]), Int.(dat[4,:])
(5, 10, [5, 3, 2, 7, 4], [2, 8, 4, 2, 5])
Upvotes: 0
Reputation: 6956
You are rebinding i
to the correct value but you are not actually updating any references within p
.
You can do something like this: p = map(i -> parse(Int, i), p)
Upvotes: 2