读取结构化文件
Reading a structured file
我写了这个简短的程序来从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((来纠正这个问题。
相关文章:
- 在基于范围的for循环中使用结构化绑定声明
- 使用结构化绑定'Reflection'
- 为什么结构化绑定不使用"auto&"返回对结构成员的引用,而是返回成员本身
- 为什么 boost::comb 对结构化绑定的支持缺少结构化绑定机制对 boost::tuples::cons 的适应?
- 结构化绑定初始值设定项表单 { 赋值表达式 } 对于 clang 上的数组类型失败
- 在 C++14 中手动实现结构化绑定
- 为什么结构化绑定不支持可变数组?
- Windows 将标准的 C 文件结构注入到正在运行的进程中
- 为<vtkDataArray> VTK 非结构化网格声明 vtkSmartPointer 类型的变量时出现问题
- 在只读(即 const)访问器上执行结构化绑定的最佳实践是什么?
- 是否有像ADTF2这样的结构化属性?
- 加载并从文件C 中加载大量的结构化数据
- 读取结构化文件
- 如何在 LabVIEW 的 DLL 中打开 OpenCV 结构化边缘检测器的模型文件?
- 尝试使用文本文件初始化多个结构变量
- 在C++中将某种结构化的文本文件读入数组
- 读取结构化二进制文件c++
- 冒泡排序在结构化列表中,由csv文件填充
- 大数据文件:读取并创建结构化文件
- 如何为结构化文件系统编写生成文件