重载运算符>>从流中读取数据

时间:2014-11-11 18:11:18

标签: c++ struct stream operator-overloading

我正在尝试重载运算符>>从流(.txt文件)中读取Comp c的数据。除了第一个数字“难度”之外,所有内容都被正确读取。它始终显示为0.

这是Comp的结构:

struct Comp
{
    string name;
    double points[7];
    double difficulty;
};

这是重载的功能>> (它应该忽略.txt文件中的额外ws):

istream& operator>>(istream& in, Comp& c)
    {
        getline(in, c.name);
        in >> ws >> c.difficulty >> ws >> c.points[0] >> ws >> c.points[1] >> ws >> c.points[2] >> c.points[3] >> ws >> c.points[4] >> ws >> c.points[5] >> ws >> c.points[6] >> ws >> c.points[7] >> ws;
        cout << c.name << endl;
        cout << c.difficulty << endl;

        return in;
    }

这是过载&gt;&gt;的函数。使用函数:

int read_competitors(istream& in, Comp V[], int n)
{
    int counter = 0;

    while (counter < n && (in >> V[counter])) {
        ++counter;
    }

    return counter;
}

最后这就是.txt文件的样子:

Anna Lindberg
2.3 6.8 7.2 6.4 8.1 2.5 6.2 7.0 
Test Name
2.3 3.4 5.6 7.8 8.5 5.4 3.6 4.7
   First Last
2.2 7.8 7.5 8.7 7.2 9.2 7.5 4.5 
Asdf Tyui
1.9 7.8 5.6 3.4 3.8 5.1 5.9 7.2
Jio Wkfjf
2.4 4.0 4.2 5.1 4.3 7.7 4.9

为什么第一个数字不能正确读取(!0)?

如果我错过了任何其他有用的信息,请告诉我。

0 个答案:

没有答案
相关问题