读取结构化文件

Reading a structured file

本文关键字:文件 结构化 读取      更新时间:2023-10-16

我写了这个简短的程序来从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 的订单。现在我被困住了,我需要帮助。谢谢。

如果将for (Purchase pp; is >> pp;)替换为

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

您可以看到代码运行良好

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

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

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

char c; is >> c;

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