读取结构化文件

时间:2018-04-10 00:16:55

标签: c++ c++11 file-io io iostream

我写了这个简短的程序,从txt文件中读取Order

struct Date
{
    int year;
    int month;
    int day;
};

istream& operator>>(istream& is, Date& d)
{
    int dd, m, y;
    char slash1, slash2;
    is >> dd >> slash1 >> m >> slash2 >> y;
    d.day = dd;
    d.month = m;
    d.year = y;
    return is;
}

class Purchase
{
public:
    string product_name;
    double unit_price;
    int count;
};

istream& operator>>(istream& is, Purchase& p)
{
    string pd;
    double price;
    int cnt;
    is >> pd >> price >> cnt;
    if (!is)
    {
        is.unget();
        is.clear(ios_base::failbit);
        return is;
    }
    p.product_name = pd;
    p.unit_price = price;
    p.count = cnt;
    return is;
}

struct Address
{
    string add;
};

istream& operator>>(istream& is, Address& a)
{
    string s;
    string aa;
    while (true)
    {
        is >> aa;
        s = s + aa + ' ';
        if (s[s.length() - 2] == '.')break;
    }
    a.add = s;
    return is;
}


class Order
{
public:
    string name;
    Address address;
    Date dt;
    vector<Purchase>purch;
};


istream& operator>>(istream& is, Order& o)
{

    string nm;
    Address aa;
    Date dd;

    is >> nm>> aa >> dd;
    if (!is)
    {
        is.unget();
        is.clear(ios_base::failbit);
        return is;
    }
    o.name = nm;
    o.address.add = aa.add;
    o.dt.day = dd.day;
    o.dt.month = dd.month;
    o.dt.year = dd.year;

    for (Purchase pp; is >> pp;)
    {
        o.purch.push_back(pp);
    }
    return is;
}

文本文件的格式如下:

John
3, Apple Street, Lagos.
11/3/2018
Soap    100 2
Cream   250 1
Cheese  50  6

Matthew
10, Orange Street, Milan.   
10/1/2018   
Tissue  50  2
Cookies 10  5
Shirts  500 2
Pen 35  1

main函数中测试此程序时:

int main()
{
    cout << "Enter input file name: ";
    string input_file;
    cin >> input_file;
    ifstream ifs{ input_file };

    vector<Order>ord;

    while (true)
    {
        Order g;
        if (!ifs)break;
        ifs >> g;
        ord.push_back(g);
    }

    cout << ord[0].name << endl;
    cout << ord[0].address.add << endl;
    cout << ord[0].dt.year << endl;
    cout << ord[0].purch[0].count << endl;
    cout << endl;
}

我发现它只会将Order的第一个实例读入ord向量。 ifstream ifs在第二次关注时失败,无法阅读新Order并突然爆发。因此,在上面的示例文件中,我只能成功阅读John的订单。现在我被困住了,我需要帮助。谢谢。

2 个答案:

答案 0 :(得分:0)

如果用

替换for (Purchase pp; is >> pp;)
int i = 0;
for (Purchase pp; is >> pp && i++ < 3;)

您可以看到代码运行种类

但是,这会产生购买量变化的问题。循环常数的大小应该是多少? 我建议在每个对象末尾的数据中使用 sentinel ,如“1”。然后您可以将循环修改为:

for (Purchase pp; is.peek() != 1 && is >> pp;)

另外,不要忘记循环后杀死下一个字符(它将是'1')

char c; is >> c;

答案 1 :(得分:0)

感谢@GillBates提供了哨兵的想法,感谢@IgorTandetnik揭露我代码中的错误部分。我能够通过在每个订单的开头使用整数索引,然后在运算符&gt;&gt;订单函数的末尾添加is.clear()来纠正这个问题。