文件处理,eof()函数

时间:2019-12-19 06:44:07

标签: c++

void Deposit()
{
    int amount, AccNo;
    cout << "DEPOSITING MONEY\n";
    cout << "Enter your account number first: ";
    cin >> AccNo;
    cout << "Enter the amount you want to deposit: ";
    cin >> amount;
    ofstream Temp("temp.bin", ios :: binary);
    Account temp;
    File.seekg(0);
    while(File.eof()){
        File.read(reinterpret_cast <char*> (&temp), sizeof(Account));
        temp.showData();
        int flag = temp.returnAccNo();
        if(AccNo == flag)
            temp.Deposit(amount);
        Temp.write(reinterpret_cast <char*> (&temp), sizeof(Account));
    }
    Temp.close();
    File.close();
    remove("Account.bin");
    rename("temp.bin", "Account.bin");
    cout << "Your deposit has been successfully done. Have a nice day! ";
    Sleep(1000);
}

为什么我不理解此Deposit()函数的作用。当调用此函数并且仅将两个对象写入文件时,此代码中的while循环将迭代3次,最后写入的对象将被写入两次。请帮忙!

1 个答案:

答案 0 :(得分:1)

您的while循环应为:

while(!File.eof())

但是使用!File.eof()条件是错误的,因为您最终将拥有未初始化的数据(eofbit将在读取结束后设置)。尝试使用

while(inputStream >> data)

可以在这里找到更详细的解释:

Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?