1 Replies - 1087 Views - Last Post: 23 March 2009 - 08:13 PM Rate Topic: -----

#1 Jayhawk  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 02-March 09

Turning data from a dat file into an array

Posted 23 March 2009 - 08:05 PM

I'm trying to read in a punch of values from a text file into an array, however I'm not sure how to go about this. The code is below. The
cout << number[1];
is supposed to echo the 2nd value of the array, but it produces some odd value. Here is the code
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main ()
{
	ifstream my_file;
	cout<<"Opening file"<<endl;
	my_file.open("numbers.dat");
	if (my_file.fail())
{
	cout << "Failed to open file." << endl;
	exit(1);
}
	int number[30], input, i = 0;
	while (my_file >> input)
	{
		  input = number[i];
		  i++;
	}
	cout << number[1];
			

	
	
	my_file.close();
	
	return 0;
}


and the numbers.dat is just the following list of values in a .dat file

11 21 32 45 52 62 71 81 92 10
95 87 71 66 54 55 34 22 11 17
85 71 61 52 46 37 28 18 91 13

Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: Turning data from a dat file into an array

#2 no2pencil  Icon User is offline

  • Admiral Fancy Pants
  • member icon

Reputation: 5395
  • View blog
  • Posts: 27,389
  • Joined: 10-May 07

Re: Turning data from a dat file into an array

Posted 23 March 2009 - 08:13 PM

	int number[30], input, i = 0;



Integers (array) number, input, & i are all assigned. Only i is given a default value, so the rest will contain whatever is currently in memory for the segments they are set in.
	while (my_file >> input)
	{


Fill input with the value of my_file
		  input = number[i];


now assign input the value of element i (which is set to zero) in the array number, which still has not been assigned a value
		  i++;
	}


Increment i
	cout << number[1];


output the 2nd element of the array number. Which again, has yet to be assigned a value.

Your guess is as good as mine as to what's in there.

That's why you are getting garbage.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1