If和Else条件都执行C ++

时间:2014-05-28 22:46:20

标签: c++

我有一个从文本文件中删除数据的功能。

输入有效输入时遇到问题:

  • 如果我输入了错误的输入,它只按预期执行else部分
  • 如果我输入有效输入,它会同时执行ifelse部分。

这是我的代码:

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!";
        }
    }
}

在输出中。如果我输入True,它会执行并显示“找不到匹配项”。 如果我输入false,它只显示“找不到匹配”及其罚款。

2 个答案:

答案 0 :(得分:10)

while(!f.eof()){几乎总是一个错误。这种情况也不例外。

eof表示您之前尝试过读取内容,但由于文件结尾而失败。如果您已经准确地读取了整个文件,那就错了,如果您在尝试读取文件之前关闭文件,就像在此示例中一样,这是错误的。如果流由于其他原因处于错误状态,则它是错误的。

相反,更改为while (f >> idList[x] >> nameList[y]),如果您因为其他原因退出循环而使用break;

答案 1 :(得分: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!";
    }
}

你的代码很糟糕。我的代码不那么糟糕。你这样做的整个方式是有缺陷的。但这是正确的做法。

相关问题