首页 > 解决方案 > 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?

标签: c++stream

解决方案


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.


推荐阅读