0

I have a function that's only purpose is to edit a file and it is not reading the correct input from the file

PAYMENT = "payment.txt"

payment.txt contains: 1 12000 200

2 26766 382.371

void Customer::makePayment()
{
    int i = 0; 
    float  monthly, payOff, payment;
    string userName;
    ifstream fin(PAYMENT);
    if (!fin.is_open())
        cout << "FILE NOT FOUND\n";
    ofstream fout(PAYMENT, ios::trunc); 
if (!fout.is_open())
        cout << "FILE NOT FOUND\n";

    while(!fin.eof())
    {   
        fin >> userName;
        fin >> payOff;
        fin >> monthly; 

        if (userName == this->userName)
        {
            cout << "payment amount: $";
            cin >> payment; 
            payOff = payOff - payment; 
        }
    
        
        fout << userName << " " << payOff << " " << monthly; 
    }
    fin.close();
    fout.close();
}

the fin is only taking in the number -107374176

  • 1
    `if (!fin.is_open())` -- `if (!fout.is_open())` -- If the input or the output file cannot be opened, your code continues on as if nothing is wrong. – PaulMcKenzie Apr 24 '23 at 01:40
  • 5
    You open the file to read, then immediately truncate it (make it empty) with the ofstream. So when you go to read it, there's nothing there. Also see [why is feof always wrong](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong), which applies equally to `eof()` in C++ – Chris Dodd Apr 24 '23 at 01:41
  • Read the file first, then when you have finished close the file and reopen it for writing. Have a file open simultaneously for reading and writing with two different stream variables is unlikely to work. – john Apr 24 '23 at 06:24
  • Maybe using two files would work , one for reading , another to writing new data in it , then remove the original file and rename new file. – Mahdy.n May 01 '23 at 20:19

0 Answers0