Reputation: 1067
below is a code I am writing to learn about using files in C++. I have everything reading and writing correctly but I can not get my display to show the correct values because it is ignoring when I try to initialize the Total variables in the while loop.
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
int customerNumber;
double beginningBalance, purchase, payments, financeCharge, endingBalance;
double beginningTotal, purchaseTotal, paymentsTotal, financeChargeTotal, endingTotal;
ifstream inputFile;
ofstream outputFile;
inputFile.open("BeginningBalance.dat");
outputFile.open("EndingBalance.dat");
cout<<"Cust No | Beginning Bal | Finance Charge | Purchases | Payments | Ending Balance"<<endl;
while (inputFile >> customerNumber)
{
outputFile <<customerNumber<<endl;
inputFile >> beginningBalance;
inputFile >> purchase;
inputFile >> payments;
financeCharge = beginningBalance * .01;
endingBlanance= beginningBalance + purchase + financeCharge - payments;
//***********************************************
//This is where I am having trouble initializing variables.
//***********************************************
beginningTotal += beginningBalance; //beginningTotal not being intitialized.
financeChargeTotal += financeCharge;
purchaseTotal += purchase;
paymentsTotal += payments;
endingTotal += endingBalance;
outputFile <<fixed<<setprecision(2)<<endingBalance<<endl;
cout<<setw(5)<<customerNumber<<fixed<<setprecision(2)<<" "<<beginningBalance<<" "<<financeCharge<<" "<<purchase<<" "<<payments<<" "<<endingBalance<<endl;
}
cout<<"Total: "<<fixed<<setprecesion(2)<<beginningTotal<<" "<<financeChargeTotal;
system ("PAUSE");
return 0;
}
Upvotes: 0
Views: 94
Reputation: 88155
beginningTotal += beginningBalance
means the same thing as
beginningTotal = beginningTotal + beginningBalance
beginningTotal is not initialized before the loop, so the first time around you get
beginningTotal = _indeterminant_value_ + beginningBalance
And so beginningTotal is always an indeterminant value. Fix it by not using uninitialized variables.
double beginningTotal = 0.0;
Upvotes: 2
Reputation:
You do not have your variables initialized in the first place, so they don't have any initial values. Then you add something to those variables, and the result is undefined (read garbage).
Consider declaring them like this:
double beginningTotal = 0, purchaseTotal = 0, paymentsTotal = 0, financeChargeTotal = 0, endingTotal = 0;
... or even better - create some structure for them.
Upvotes: 5