Here is my problem, I’m trying to read in data from a file "beginningbalance.dat", containing the following:
111
100.00
200.00
50.00
222
200.00
300.00
100.00
What I want to do is read in 111 for customer_number[0] and 222 for customer_number[1]. For new_balance[0], I want to add the values of the 3 numbers under 111 and new_balance[1] the numbers under 222.
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int count = 0;
double val1, val2, val3, sum;
int customer_number[2];//Array for holding customer number from file.
double new_balance[2];//Array for holding added values from file.
ifstream beginning_balance;
beginning_balance.open("beginningbalance.dat");
while(beginning_balance)
{
beginning_balance >> customer_number[count];
beginning_balance >> val1;
beginning_balance >> val2;
beginning_balance >> val3;
sum = val1+val2+val3;
new_balance[count] = sum; //Supposed to read in customer id number then 3 values from files, then starts itself over and reads a new customer number for the new array element.
count++; //
}
cout<<val1<<" "<<val2<<" "<<val3<<"\n\n";//Testing values being read in
cout<<"Customer Number #"<<customer_number[0]<<endl;//Should read Customer Number # 111
cout<<"New Balance $"<<new_balance[0]<<endl;
cout<<"Customer Number #"<<customer_number[1]<<endl;//Should read Customer Number # 222
cout<<"New Balance $"<<new_balance[1]<<endl;
system("pause");
return 0;
}
My output is
100 -858993460 -858993460
Customer Number #111
New Balance $-1.71799e+009
Customer Number #0
New Balance $5.48413e-322
Press any key to continue...
{I had my val1,val2,val3,and sum set to int when it should have been something to allow floating point numbers, I also only allowed 1 element for each array.}
This might not be the whole bug, but it’s at least part of it:
You’ve declared these
[1]which means “1 element with index 0”. If you want indexes 0 and 1 then you should use[2]. By overrunning your array bounds you’re corrupting the memory of other variables nearby, which probably explains the bad balance values. (But maybe not the bad val2 and val3 values.)However since your code allows you to read in an arbitrary number of data sets you should consider using an stl::vector or similar for these, or probably an stl::vector of a structure / class that contains the customer number and balance as a single object.