流的定位tellg() / tellp()、seekg() / seekp()

获取流位置

– tellg() / tellp() 可以用于获取输入 / 输出流位置 (pos_type 类型 )
– 两个方法可能会失败,此时返回 pos_type(-1)

**tellp()**返回当前关联的 streambuf 对象的输出位置指示器。
若出现失败则为 pos_type(-1) 。

示例:

#include <iostream>
#include <sstream>
int main()
{
    std::ostringstream s;
    std::cout << s.tellp() << '\n';
    s << 'h';
    std::cout << s.tellp() << '\n';
    s << "ello, world ";
    std::cout << s.tellp() << '\n';
    s << 3.14 << '\n';
    std::cout << s.tellp() << '\n' << s.str();
}

输出:

0
1
13
18
hello, world 3.14

tellg()返回当前关联的 streambuf 对象的输入位置指示器。
成功时为获取指针的当前位置,失败时为 pos_type(-1) 。

示例:

#include <iostream>
#include <string>
#include <sstream>
 
int main()
{
    std::string str = "Hello, world";
    std::istringstream in(str);
    std::string word;
    in >> word;
    std::cout << "After reading the word \"" << word
              << "\" tellg() returns " << in.tellg() << '\n';
}

输出:

After reading the word "Hello," tellg() returns 6

设置流位置

– seekg() / seekp() 用于设置输入 / 输出流的位置
– 这两个方法分别有两个重载版本:
● 设置绝对位置:传入 pos_type 进行设置
● 设置相对位置:通过偏移量(字符个数 ios_base::beg ) + 流位置符号的方式设置
– ios_base::beg
– ios_base::cur
– ios_base::end
参数
pos - 设置输入位置指示器到的绝对位置。
off - 设置输入位置指示器到的相对位置。
dir - 定义应用相对偏移到的基位置。它能为下列常量之一:
常量 解释
beg 流的开始
end 流的结尾
cur 流位置指示器的当前位置

示例:
basic_istream& seekg( pos_type pos );
basic_istream& seekg( off_type off, std::ios_base::seekdir dir);

#include <iostream>
#include <string>
#include <sstream>
 
int main()
{
    std::string str = "Hello, world";
    std::istringstream in(str);
    std::string word1, word2;
 
    in >> word1;
    in.seekg(0); // 回溯
    in >> word2;
 
    std::cout << "word1 = " << word1 << '\n'
              << "word2 = " << word2 << '\n';
}

输出:

word1 = Hello,
word2 = Hello,

basic_ostream& seekp( pos_type pos );
basic_ostream& seekp( off_type off, std::ios_base::seekdir dir );

示例:

#include <sstream>
#include <iostream>
 
int main()
{
    std::ostringstream os("hello, world");
    os.seekp(7);
    os << 'W';
    os.seekp(0, std::ios_base::end);
    os << '!';
    os.seekp(0);
    os << 'H';
    std::cout << os.str() << '\n';
}

输出:

Hello, World!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值