I think I have a memory problem since this code keeps outputting large negative numbers. The file that it reads includes- lastname, firstname, identification number, then 5 decimal numbers. ZDoes anyone know what the problem is?

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>

using namespace std;

const int rows = 5;
const int cols = 5;

int main()
{	
	ifstream inData;
	string lastname, firstname;
	int identity[5];
	int number=0;
	int i,j;
	int subject;
	float sum=0,total;
	float numbers[rows][cols];
	

	inData.open("data.txt");

	while (inData)
	{
		inData>>lastname>>firstname>>identity[number];
		
		for (i=0; i<rows; i++)
		{
			cout<<lastname<<" "<<setw(2)<<firstname<<" "<<identity[number]<<" ";
            for (j=0; j<cols; j++)
            { 
	         inData >> numbers[i][j];
	         cout<<fixed<<setprecision(1)<<setw(5)<<numbers[i][j]<<" ";
			 sum=sum+numbers[i][j];
            }
			cout<<setw(5)<<sum/8;
			sum=0;
			cout<<endl;
		}
cout<<endl;
				
	}

inData.close();

return 0;
}

1) The while statement is incorrect

while( inData>>lastname>>firstname>>identity[number] )
{
   // other code here
}

2) you don't want that i loop because it is attempting to read (rows*cols) number of numbers for each name. All you want it to do is read the columns for each name.

int i = 0;
while( inData>>lastname>>firstname>>identity[number] )
{
     sum = 0;
     for(j = 0; j < cols; j++)
     {
          inData >> numbers[i][j];
          sum += numbers[i][j];
    }
    cout << sum << "\n";
    i++;
    number++;
}

3) you are keeping all the integers and floats in an array for all names, but you don't keep the names ? Any reason for doing that? If you don't need the names then why not just toss the numbers for those names too?

4) rename either number or numbers to something else because they are confusing.

Yeah that makes sense, thanks for the help...again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.