流中的输入位置和输出位置有什么区别?

What is difference between input position and output position in streams?

本文关键字:位置 什么 区别 输出 输入      更新时间:2023-10-16

输入位置和输出位置在basic_iostream有区别吗?

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

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

有关更多信息,请参阅 seekg 和 seekp 的文档。

问题是为什么我们需要两个位置? 某些对象扮演双重角色,您可以以交错方式读取和写入它们。参见 std::stringstream,它同时实现了 istream 和 ostream std::stringstream ss; SS<<"哈洛"; 填充缓冲区并在 hallo 末尾(尾部(设置输出位置,但输入位置(头部(仍为 0。所以可以从中读取一些东西。 它是队列的实现。