在istream_iterator中使用后的c++ fstream obj回滚

标签 c++ io fstream istream-iterator

如何重置迭代器状态或在其他istream_iterator 中使用istream_iterator 使用的fstream obj。我在 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++;

跳过重复项。

最佳答案

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

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

关于在istream_iterator中使用后的c++ fstream obj回滚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797424/

相关文章:

c++ - 创建从现有派生的新异常

c++ - DirectX/C++ : Marching Cubes Indexing

c - 从文件或标准输入读取

c++ - 从文本文件中读取信息并将其正确存储在数组中,int

c++ - 指定调用 std::copy 的小数精度

c++ - 为 Visual Studio 2017 构建 boost 1.64

c++ - 标准库警告是否正常?

ruby - 在 ruby​​ 脚本中打开文本编辑器

c# - 非阻塞 io 函数而不是 cin.get()

c++ - 如何使用 C++ 中的写入函数将 float 转换为 char 以写入文件?