【问题标题】:c++ fstream obj rollback after using in istream_iteratorc ++ fstream obj在istream_iterator中使用后回滚
【发布时间】:2018-08-11 07:17:16
【问题描述】:

如何重置迭代器状态或使用fstream obj,它被istream_iterator 使用,其他istream_iterator。我在fstream obj 上尝试了seekp(ios_base::begin)clear() 方法,但这没有任何影响。

main(){
    fstream ofs{"219.txt"};
    fstream ofstl{"219-.txt"};

    ofstream rezult{"219-rezult.txt"};

    istream_iterator<string> begf{ofs};
    istream_iterator<string> begs{ofstl};
    istream_iterator<string> end;

    ostream_iterator<string> outr{rezult, "\n"};

    merge(begf, end, begs, end, outr);    // using iterators

    ofs.seekp(ios_base::beg);       // does not affect
    ofs.clear();                    // does not affect

    while(begf!=end){
        cout<<*begf;                // work only once
        begf++;
    }

    istream_iterator<string> begff{ofs};        // new iterator
    while(begff!=end){
        cout<<*begff;               // dont work even once
        begff++;
    }
}

更新:
如果我使用

ofs.clear();
ofs.seekp(ios_base::beg); 

然后继续使用相同的istream_iterator第一次和第二次取消引用给出相同的值,所以需要使用

begf++;

跳过重复项。

【问题讨论】:

    标签: c++ io fstream istream-iterator


    【解决方案1】:

    seekp 之前调用clear,因为有seekp 未处理的失败和/或eof 位

    ofs.clear();
    ofs.seekp(ios_base::beg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 2012-08-04
      相关资源
      最近更新 更多