C++ streambuf::pubseekpos() 函数



C++ 的 std::streambuf::pubseekpos() 函数用于设置流缓冲区中下一个要读取或写入字符的位置。此函数通常用于在流中查找,从而可以随机访问数据的不同部分。

此函数在成功时返回新位置,在失败时返回 pso_type(-1)。

语法

以下是 std::streambuf::pubseekoff() 函数的语法。

pos_type pubseekpos (pos_type pos, ios_base::openmode which = ios_base::in | ios_base::out);

参数

  • pos &minius; 它指示位置指针的新绝对位置。
  • which - 它通常用于确定将在哪个受控序列上修改位置。

返回值

此函数返回修改后的位置指针的新位置值。

异常

如果抛出异常,则流缓冲区处于有效状态。

数据竞争

它修改流缓冲区对象。

示例 1

在下面的示例中,我们将考虑 pubseekpos() 函数的基本用法。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("Welcome");
   a.pubseekpos(10);
   std::cout << a.str().substr(a.pubseekpos(2)) << std::endl;
   return 0;
}

输出

以下是上述代码的输出 -

lcome

示例 2

考虑以下示例,我们将修改流内容。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf buffer("XYZDEFG");
   buffer.pubseekpos(0);
   buffer.sputn("ABC", 3);
   std::cout << buffer.str() << std::endl;
   return 0;
}

输出

上述代码的输出如下 -

ABCDEFG

示例 3

让我们看下面的示例,我们将重置流的位置。

#include <iostream>
#include <sstream>
int main() {
   std::stringbuf a("ABCDEFGH");
   a.pubseekpos(0);
   std::cout << a.str().substr(a.pubseekpos(6)) << std::endl;
   a.pubseekpos(0);
   std::cout << a.str().substr(a.pubseekpos(0)) << std::endl;
   return 0;
}

输出

如果我们运行上述代码,它将生成以下输出 -

GH
ABCDEFGH
streambuf.htm
广告

© . All rights reserved.