c++ - How to save and extract custom data from streams?
问题描述
I am saving data with ofstream
to a file and trying to extract from it with ifstream
.
Only the saving process works, but when I try to extract it's starting to give me garbage data.
I want to save this way using ofstream
ofstream & operator<<(ofstream &ofs, Item &i){
ofs<<"Item name "<<i.name<<endl;
ofs<<"Item price "<<i.price<<endl;
ofs<<"Item quantity "<<i.qty<<endl;
return ofs;
}
In the main method
ofstream ofs("Items.txt",ios::trunc)
vector<Item *>::iterator itr;
for(itr=list.begin(); itr!=list.end(); itr++){
ofs<<**itr;
}
It's work perfectly fine when I check Items.txt.
It fails to extract using ifstream
ifstream & operator>>(ifstream &ifs, Item &i){
ifs>>i.name>>i.price>>i.qty;
return ifs;
}
I try to do this way ifs>>"Item name ">>i.name>>endl;
But this gave me compiler error.
In Main Method
Item item;
ifstream ifs("Items.txt");
ifs>>item;
for(int i=0; i<n; i++){
cout<<item<<endl;
}
In case you are wondering about cout<<item<<endl;
, I just create
ostream & operator<<(ostream &os, Item &i){
os<<"Item name "<<i.name<<endl;
os<<"Item price "<<i.price<<endl;
os<<"Item quantity "<<i.qty<<endl;
return os;
}
I don't know how to exact custom data using ifstream.
Can anyone help, thanks?
解决方案
This should work
istream & operator>>(istream &ifs, Item &i) {
string dummy;
ifs >> dummy >> dummy >> i.name
>> dummy >> dummy >> i.price
>> dummy >> dummy >> i.qty;
return ifs;
}
The purpose of the dummy
variable is to read (and discard) the extra labels you added to the output Item name
etc.
If you wanted to go further you could also add checks that the extra information is as you expected and signal an error if it is not.
Note that operator>>
should work on istream
not ifstream
. Some day you might want to read from some input other than a file, and since istream
works with files and with other kinds of input there's nothing lost by using istream
.
Similarly operator<<
should work on ostream
not ofstream
.
In other words there's no need to duplicate your operator>>
and operator<<
, by using just istream
and ostream
they'll work with all kinds of input and output.
推荐阅读
- c# - 初始化预制件实例的变量
- javascript - 选择时 Jquery 自动完成提交表单 - 为什么此代码不起作用?
- css - 页面内容之间的神秘白线
- javascript - d3 fitSize 不符合使用 geojson 多边形的预期范围
- html - 控制器未在 index.html 上的 HTMLInputElement.onclick 中定义
- flutter - 在 DataTable 构建器中将 Map 转换为 List 的多个问题
- debian - Debian Buster 上的“设备上没有剩余空间”错误,/dev/sda1 100% Full
- hyperlink - 如何解决灯塔的代码问题“AVADA WordPress 主题”问题
- html - 如何让 2 个悬停效果同时工作?
- python - URL 在浏览器中有效,但在使用 requests.get 方法时无效