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;
}
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:
… or even better – create some structure for them.