【问题标题】:How to save and extract custom data from streams?如何从流中保存和提取自定义数据?
【发布时间】:2020-07-05 07:48:29
【问题描述】:

我正在使用ofstream 将数据保存到一个文件,并尝试使用ifstream 从中提取数据。 只有保存过程有效,但当我尝试提取时,它开始给我垃圾数据。

我想用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;
}

在main方法中

ofstream ofs("Items.txt",ios::trunc)
vector<Item *>::iterator itr;
for(itr=list.begin(); itr!=list.end(); itr++){
          ofs<<**itr;
}

当我检查 Items.txt 时,它工作得非常好。

使用ifstream提取失败

ifstream & operator>>(ifstream &ifs, Item &i){
       ifs>>i.name>>i.price>>i.qty;
       return ifs;
}

我尝试这样做ifs&gt;&gt;"Item name "&gt;&gt;i.name&gt;&gt;endl; 但这给了我编译器错误。

在主方法中

Item item;
ifstream ifs("Items.txt");
ifs>>item;

for(int i=0; i<n; i++){
     cout<<item<<endl;
}

如果你想知道cout&lt;&lt;item&lt;&lt;endl;,我只是创建

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;
}

我不知道如何使用 ifstream 来精确自定义数据。

谁能帮忙,谢谢?

【问题讨论】:

  • It fails to extract using ifstream:这是编译错误还是运行时错误?
  • 编译错误。 exec.cpp:38:5: error: invalid operands to binary expression ('std::__1::ifstream' (aka 'basic_ifstream&lt;char&gt;') and 'const char [15]') ifs&gt;&gt;"Item qunatity "&gt;&gt;i.qty&gt;&gt;endl; ~~~^ ~~~~~~~~~~~~~~~~

标签: c++ stream


【解决方案1】:

这应该可以工作

istream & operator>>(istream &ifs, Item &i) {
    string dummy;
    ifs >> dummy >> dummy >> i.name 
        >> dummy >> dummy >> i.price
        >> dummy >> dummy >> i.qty;
    return ifs;
}

dummy 变量的用途是读取(并丢弃)您添加到输出 Item name 等的额外标签。

如果您想更进一步,您还可以添加检查额外信息是否符合您的预期,如果不是,则发出错误信号。

请注意,operator&gt;&gt; 应该适用于 istream 而不是 ifstream。有一天,您可能希望从文件以外的某些输入中读取数据,并且由于 istream 可以处理文件和其他类型的输入,因此使用 istream 不会丢失任何内容。

同样operator&lt;&lt; 应该适用于ostream 而不是ofstream

换句话说,无需复制您的operator&gt;&gt;operator&lt;&lt;,只需使用istreamostream,它们就可以处理各种输入和输出。

【讨论】:

  • @realNameDoesn'tExist 因为Item name 是两个单词,每个dummy 只会读取一个单词。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 1970-01-01
  • 2021-12-11
  • 2016-08-04
  • 1970-01-01
  • 2013-07-07
相关资源
最近更新 更多