简体   繁体   中英

C++ Reading in wrong values from a file

My data file contains the following numbers to be read in

/*
111
100.00
200.00
50.00
222
200.00
300.00
100
*/

but after the while loop reads in customerNumber as 100 when it should be 111, it get's the values for everything else wrong also. Such as beginningBalance reading as

//-9255963134931783000000000000000000000000.00 

and everything else seems to be reading the same value. I'm just learning about files so any help would be greatly appreciated.

#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;

int main()
{

int customerNumber;
double beginningBalance, purchase, payments, financeCharge, endingBalance;
ifstream inputFile;
ofstream outputFile;

inputFile.open("BeginningBalance.dat");
cout<<"Cust No | Beginning Bal | Finance Charge | Purchases | Payments | Ending Balance"<<endl;

while (inputFile >> customerNumber);
    {
     inputFile >> beginningBalance;
     inputFile >> purchase;
     inputFile >> payments;
     financeCharge = beginningBalance * .01;
     endingBalance = beginningBalance + purchase + financeCharge - payments;
     cout<<setw(5)<<customerNumber<<fixed<<setprecision(2)<<"        "<<beginningBalance<<"        "<<financeCharge<<"          "<<purchase<<"       "<<payments<<"       "<<endingBalance<<endl;
    }


system ("PAUSE");
return 0;
}

Try removing the semicolon from after your while loop condition and see if that fixes it.

So change

while (inputFile >> customerNumber);

to

while (inputFile >> customerNumber)

The way it is now, it does nothing until it eats up all the data from the file, then does the stuff inside the { ... } , and the file reads you do in there are already at EOF so they don't work.

The /* at the beginning of the file is corrupting your data. Either remove the /* or account for them by reading in two junk characters before your read your customer number.

Also you have a semicolon after your while loop statement that you need to remove.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM