-2
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);
}

Why this Deposit() function not working, I don't understand. When this function is called and only two objects have been written into the file, the while loop in this code iterates three times and the last object that is written is written twice. Please help!!

kuro
  • 2,585
  • 1
  • 12
  • 23
Sam_
  • 33
  • 4
  • 4
    What is `Account`? Is it a [POD-type class](https://en.cppreference.com/w/cpp/named_req/PODType) without any pointers? Otherwise you can't use it in a raw binary file. Also please read [Why is iostream::eof inside a loop condition (i.e. `while (!stream.eof())`) considered wrong?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons) – Some programmer dude Dec 19 '19 at 06:48
  • Add your full code in here – Kalana Dec 19 '19 at 06:58
  • Account is a class type. And is there an alternative to eof() to stop the file read at the end?(And there's a '!' before File.eof() in the condition.) – Sam_ Dec 19 '19 at 07:01
  • An alternative, is to use the return value of [`read`](https://en.cppreference.com/w/cpp/io/basic_istream/read), but you should address Someprogrammerdude's comment, first, and provide a [mre]. – Bob__ Dec 19 '19 at 07:18

1 Answers1

1

Your while loop should be:

while(!File.eof())

But using the !File.eof() condition is wrong because you will end up having uninitialized data (the eofbit will be set after reading the end). Try using

while(inputStream >> data)

A more detailed explanation can be found here:

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

Remy Lebeau
  • 454,445
  • 28
  • 366
  • 620
Theodor Badea
  • 465
  • 2
  • 9
  • Thank u. I put the read function in the condition part of while loop and it worked^_^. – Sam_ Dec 20 '19 at 07:35