0

我已经写了一些东西到文件中,现在我想在屏幕上阅读和查看内容。我编写了要查看的函数,但它没有显示任何内容。这是视图函数的代码。我正在测试只查看2个变量。底部调用的显示函数来自父类,它显示其他类的所有变量

void ViewAll(string name, Intervention inte)
{
    ifstream clientfile(name, ios::in);
    if (clientfile)
    {
        int hour, min, day, month, yr, snum, age;
        string fname, lname, interNo, problem, clinic, area, ex,  li,                    type,      breed, gender, sname, town, pay;

        while (clientfile && !clientfile.eof())
        { //needed to loop through each record in the file
            clientfile >> interNo;
            clientfile >> clinic;
            clientfile >> lname;
            clientfile >> fname;
            clientfile >> pay;
            clientfile >> snum;
            clientfile >> sname;
            clientfile>> town;
            clientfile >> area;
            clientfile >> ex;
            clientfile >> li;
            clientfile >> type;
            clientfile >> breed;
            clientfile >> gender;
            clientfile >> problem;
            clientfile >> age;
            clientfile >> day;
            clientfile >> month;
            clientfile >> yr;
            clientfile >> hour;
            clientfile >> min;

            if (fname == inte.getClient().getFname())
            {
                break;
            }
        }

        //after record is found, create record
        inte.getClient();
        inte.display();
        system("pause");
    }

    //return inte;
}
4

2 回答 2

0

你想读懂 inte 的成员吗?如果是这样,您将必须通过引用传递 inte 以便您可以修改传递的对象,然后读取为

clientfile >> inte.interNo;

您创建的所有这些局部变量似乎都是无用的。

于 2013-11-03T02:53:02.087 回答
0

作为一个起点,我建议以不同的方式构建代码。我将从重载operator>>operator<<分别读取和写入数据Intervention开始:

std::istream &operator>>(std::istream &is, Intervention &i) { 
        is >> i.interNo;
        is >> i.clinic;
        is >> i.lname;
        is >> i.fname;

        // ...

        is >> i.min;
        return is;
}

...并相应地operator<<

std::ostream &operator>>(std::ostream &os, Intervention const &i) { 
        os << i.interNo;
        os << i.clinic;
        os << i.lname;
        os << i.fname;

        // ...

        os << i.min;
        return os;
}

有了这些,我们可以显示文件中的所有记录,只需调用std::copyusingistream_iteratorostream_iterator

std::ifstream in(name);

std::copy(std::istream_iterator<Intervention>(in),
          std::istream_iterator<Intervention>(),
          std::ostream_iterator<Intervention>(std::cout, "\n"));

这消除了您的代码包含的一些问题,例如尝试使用:

while (clientfile && !clientfile.eof())

类似的代码while (!somefile.eof())几乎是一个可以保证的错误(“几乎”只是因为可以编写其他代码来掩盖该代码不能也不能正常工作的事实)。

于 2013-11-03T04:43:06.700 回答