0

Hey, I am trying to read in a random number of ints from a file into an array of pointers, while also incrementing the size of the array to match the number of new ints...

I have come up with this piece of code which somehow works, but doesnt store the values in memory, when i try to print them out somewhere else i just get a lot of 0's

int* scores;	
           int counter = 0;
	while(!ins.eof())
	{
		scores = new int[counter+1];
		ins >> scores[counter];
		cout << scores[counter] << endl;
		counter++;
	}
	
	for( int i = 0; i < counter; i++)
	{
		cout << scores[i] << endl;
	}

it will print out the correct number in the while loop, but prints out 0's in the for loop, please help me

the txt file its reading from just has a few ints each on a new line like
23
12
5
21...

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by ithelp
0
int* scores;	
           int counter = 0;
	while(!ins.eof())
	{
		scores = new int[counter+1];
		ins >> scores[counter];
		cout << scores[counter] << endl;
		counter++;
	}

The line: scores = new int[counter+1]; is creating a new int array, where all elements are initialised to 0. You will therefore have to copy the data from the old array into the new array and then free the memory used by the old array using delete[]. You may then assign the new data using your line: ins >> scores[counter];

You may want to use vector<int>, list<int>, etc. to perform the above function more elegantly (and with less room for mistakes).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.