【问题标题】:What is difference between input position and output position in streams?流中的输入位置和输出位置有什么区别?
【发布时间】:2018-09-19 03:05:29
【问题描述】:

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

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

【问题讨论】:

标签: c++ stream


【解决方案1】:

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 的文档。

【讨论】:

    【解决方案2】:

    问题是为什么我们需要两个职位? 有些对象扮演双重角色,您可以以交错的方式读取和写入它们。参见 std::stringstream,它同时实现了 istream 和 ostream std::stringstream ss; ss

    【讨论】:

      猜你喜欢
      • 2014-09-14
      • 1970-01-01
      • 2015-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多