Memory Problem?
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;
}
JackDurden
Junior Poster in Training
92 posts since Jun 2008
Reputation Points: 10
Solved Threads: 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 eithernumber or numbers to something else because they are confusing.
Ancient Dragon
Retired & Loving It
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
Yeah that makes sense, thanks for the help...again!
JackDurden
Junior Poster in Training
92 posts since Jun 2008
Reputation Points: 10
Solved Threads: 0