Reputation: 71
Okay, so I am making a game that reads data from a text file to create events. What happens is as each year advances if something exciting happens a popup box with three options appears, clicking them affects the game and so on.
I have created a function which can take various arguments and make the form automatically - so far so good- but writing large event descriptions in the code is messy and disorganized. Instead I decided to create another function which takes values from a text file, organizes them and then calls the second function to create the 'event'.
Now, as I said each event comes with three choices (See below) and each choice has a consequence on one of three factors (approval, prestige, power), I haven't quite worked out the mechanics properly but all in good time, everything runs wonderfully until I need to load this integers from the text file.
It keeps having trouble converting the string to an integer, why is this and how can I fix it?
Line 11 of the text file: 10 (yes I checked and it is the right line to read)
The code:
List<int> affecta = new List<int>();
affecta.Add(Int32.Parse(System.IO.File.ReadLines(filename).Take(11).First()))
I can load the other things such as the picture file's location perfectly, so 'filename' points to the correct .txt
It might be something really obvious to someone with more experience, but I just can't see why.
Upvotes: 1
Views: 68
Reputation: 21887
I don't think Take
does what you think - It grabs the first 11 items and returns all of them, so you get an IEnumerable
of 11 items. When you do First
on that, you get item at position 0, not position 10. I think you want Skip
and then First
, which will skip the first 10 items and return the next (11th) item:
affecta.Add(Int31.Parse(System.IO.File.ReadLines(filename).Skip(10).First()))
Upvotes: 4
Reputation: 281
Take(11).First()
returns the First element from the IEnumerable containing the 11 elements.
Instead, Skip the first 10 and select the First from the IEnumerable.
affecta.Add(Int32.Parse(System.IO.File.ReadLines(filename).Skip(10).First()))
Alternatively, Take the first 11 and select the Last from the IEnumerable.
affecta.Add(Int32.Parse(System.IO.File.ReadLines(filename).Take(11).Last()))
Upvotes: 0
Reputation: 31153
If you use Take(11)
this means "get 11 rows from the source". After that you have First()
, so you'll get first of them. You're essentially trying to convert the first line into integer.
I assume you want to use Skip(10)
since you want the 11th line.
Upvotes: 2