• Post Reply Bookmark Topic Watch Topic
  • New Topic

Need help with reading multiple lines from a txt file and putting them into an array  RSS feed

 
Dan Rana
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i'm trying to read in numbers from a file and then store them into an array. I get the right size array, but it prints out all 0's.

ex: the file looks like this:
1
2
3

the output is supposed to be [1, 2, 3] but i get [0, 0, 0]

 
Nicola Garofalo
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Start by putting the initialization of your int var i out of the while loop.

Or you will always set arr[0]

I mean



change to:

 
Dan Rana
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ah. good catch, but i still get all 0's.
 
Nicola Garofalo
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yuo perform two loops to read values from a file. Why?
 
Dan Rana
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nicola Garofalo wrote:Yuo perform two loops to read values from a file. Why?


the first while loop was to determine the length of the array and the second was to store the ints into separate parts of the array
 
Nicola Garofalo
Ranch Hand
Posts: 308
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice,are you sure that the second loop will be performed?
 
Dan Rana
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nicola Garofalo wrote:Nice,are you sure that the second loop will be performed?


are you a teacher? haha this bit of advice helped me out. this worked out:
 
Nicola Garofalo
Ranch Hand
Posts: 308
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok, do you need arrays or you can store values in Lists?
That would avoid a double file scan.

Anyway, happy you solved your problem
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!