流中输入位置和输出位置之间的区别是什么?

时间:2018-09-19 03:05:29

标签: c++ stream

basic_iostream中的输入位置和输出位置之间是否存在差异?

如果我将字节放入流中并且想要读取它们,我应该使用seekg()seekp()开头读取什么?

1 个答案:

答案 0 :(得分:0)

seekg设置当前关联的streambuf对象的输入位置指示器。

seekp设置当前关联的streambuf对象的输出位置指示器。

使用seekg,您可以将指示器设置在所需的位置并从该位置读取。

例如,seekg(0)将倒带到streambuf对象的开头,您可以从开头开始阅读。

这是一个简单的示例:

#include <iostream>
#include <string>
#include <sstream>
 
int main()
{
    std::string str = "Read from Beginning";
    std::istringstream in(str);
    std::string word1, word2, word3;
 
    in >> word1;
    in.seekg(0); // rewind
    in >> word2;
    in.seekg(10); // forward
    in >> word3;
 
    std::cout << "word1 = " << word1 << '\n'
              << "word2 = " << word2 << '\n'
              << "word3 = " << word3 << '\n';
}

输出为:

word1 = Read
word2 = Read
word3 = Beginning

有关更多信息,请参见seekgseekp的文档。