0

I have a function for deleting data from a text file.

I'm having problems when valid input is entered:

  • if I enter bad input, it only executes the else part, as expected
  • if I enter valid input, it executes both the if and the else part.

Here is my code:

void Member::processTransaction()
{
    fstream f;

    f.open("Member.txt",ios::in|ios::out);

    int x = 0, y = 0, z = 0;

    while (!f.eof())
    {
        f >> idList[x] >> nameList[y];

        if (id == idList[x])
        {
            cout << idList[x] << "\t" << nameList[x] << endl;

            cout << "Do you want to delete the entry (Y/N) : " << endl;

            char deleteEntry = getche();

            if(deleteEntry=='Y'||deleteEntry=='y')
                deleteInformation();  

            f.close();
        }
        else
        {
            cout << "No Matches Found!";
        }
    }
}

in the output. If I enter True, it executes and displays "No Matches Found". If I enter false, it only displays "No Matches Found" and its fine.

Gustavo Mori
  • 8,319
  • 3
  • 38
  • 52
IamBatman
  • 77
  • 11

2 Answers2

10

while(!f.eof()){ is almost always a mistake. This case is no exception.

eof means you tried to read something previously, and it failed due to end of file. It's false if you have read the whole file exactly, and it's false if you close the file before trying to read past the end as you do in this example. And it's false if the stream is in an error state for another reason.

Instead , change to while (f >> idList[x] >> nameList[y]), and use break; if you want to exit the loop for some other reason than this read failing.

M.M
  • 138,810
  • 21
  • 208
  • 365
0
void Member::processTransaction() {
    fstream f;
    f.open("Member.txt", ios::in | ios::out);
    int x = 0, y = 0, z = 0;
    bool found = false; // found or not?
    // search the file now.
    while(!f.eof() && !found) {
        f >> idList[x] >> nameList[y];
        if(id != idList[x]) {
            continue;
        }
        cout << idList[x] << "\t" << nameList[x] << endl;
        cout << "Do you want to delete the entry (Y/N) : " << endl;
        char deleteEntry = getche();
        if(deleteEntry == 'Y' || deleteEntry == 'y') {
            deleteInformation();
        }
        found = true;
    }
    f.close(); // close here
    // not found only after you're done searching.
    if(!found) {
        cout << "No Matches Found!";
    }
}

Your code is bad. My code is just less bad. Your entire way of doing this is flawed. But this is the right wrong way to do it.

CodeAngry
  • 12,760
  • 3
  • 50
  • 57