从文件中读取错误的值

C++ Reading in wrong values from a file

本文关键字:取错误 读取 文件      更新时间:2023-10-16

我的数据文件包含以下要在

中读取的数字
/*
111
100.00
200.00
50.00
222
200.00
300.00
100
*/

但是当while循环读取customerNumber为100时,它应该是111,它也得到了其他所有错误的值。例如beginningBalance读取为

//-9255963134931783000000000000000000000000.00 

和其他所有内容似乎都在读取相同的值。我正在学习有关文件的知识,如果有任何帮助,我将不胜感激。

#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;
}

尝试从while循环条件后面删除分号,看看是否可以修复它。

所以改变

while (inputFile >> customerNumber);

while (inputFile >> customerNumber)

现在的方式是,它什么也不做,直到它从文件中吃掉所有的数据,然后{ ... }内部的东西,你在那里做的文件读取已经在EOF,所以他们不工作。

文件开头的/*正在破坏您的数据。要么删除/*,要么在读取客户号之前读入两个垃圾字符来解释它们。

在while循环语句后面还有一个分号需要删除。