【问题标题】:Both If and Else condition execute C++ [duplicate]If和Else条件都执行C ++ [重复]
【发布时间】:2014-07-18 08:30:13
【问题描述】:

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

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

  • 如果我输入错误的输入,它只会按预期执行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,它只会显示“未找到匹配项”并且很好。

【问题讨论】:

  • 也许你应该在f.close();之后添加一个break;
  • 替换 f.close()breakreturnfstream 析构函数关闭文件。
  • 如果实际上没有找到匹配项,no matches found 应该退出循环。您这样做的方式不会处理托管多组输入变量的文件。
  • @MikeChristensen 我用过break;但它没有用。
  • while (!f.eof()) 不不不不

标签: c++


【解决方案1】:

while(!f.eof()){ 几乎总是一个错误。本案也不例外。

eof 表示您之前尝试读取某些内容,但由于文件结尾而失败。如果您已准确读取整个文件,则为错误;如果您在尝试读取文件末尾之前关闭文件,则为错误,就像在本示例中所做的那样。如果流由于其他原因处于错误状态,则为 false。

如果您因为读取失败以外的其他原因想要退出循环,请改为使用while (f &gt;&gt; idList[x] &gt;&gt; nameList[y]),并使用break;

【讨论】:

    【解决方案2】:
    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!";
        }
    }
    

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

    【讨论】:

    • 我在你的代码中也看到了他代码中的大部分明显错误,你的代码如何不那么糟糕?
    • @MooingDuck 这段代码就像一个笑话。你不解释。但你会弄明白的。
    • @CodeAngry 不过这不是一个好笑话。
    • @Massa 这段代码不会把这两个东西都打印出来。如果找到,则不会打印No matches,因为它没有在循环内进行测试。这是唯一的事情。加上文件在循环外关闭。
    猜你喜欢
    • 2021-11-06
    • 1970-01-01
    • 2022-12-14
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多