c++11 标准模板(STL)(std::basic_istream)(九)

定义于头文件 <istream>
template<

    class CharT,
    class Traits = std::char_traits<CharT>

> class basic_istream : virtual public std::basic_ios<CharT, Traits>

 类模板 basic_istream 提供字符流上的高层输入支持。受支持操作包含带格式的输入(例如整数值或空白符分隔的字符与字符串)和无格式输入(例如未处理字符和字符数组)。此功能以通过 basic_ios 基类访问的底层 basic_streambuf 类所提供的接口实现。大多数库实现中, basic_istream 有一个非继承数据成员:用于存储 basic_istream::gcount() 所返回的值。


寻位

返回输入位置指示器

std::basic_istream<CharT,Traits>::tellg

pos_type tellg();

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

表现为无格式输入函数 (UnformattedInputFunction) ,除了不影响 gcount() 。构造并检查 sentry 对象后,若 fail() == true ,则返回 pos_type(-1) 。否则,返回 rdbuf()->pubseekoff(0, std::ios_base::cur, std::ios_base::in) 。

参数

(无)

返回值

成功时为获取指针的当前位置,失败时为 pos_type(-1) 。

异常

若出现错误(错误状态标志不是 goodbit )并且设置了 exceptions() 为对该状态抛出则为 failure 。

若内部操作抛出异常,则捕获它并设置 badbit 。若对 badbit 设置了 exceptions() ,则重抛该异常。

调用示例

#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';
}

输出

设置输入位置指示器

std::basic_istream<CharT,Traits>::seekg

basic_istream& seekg( pos_type pos );

basic_istream& seekg( off_type off, std::ios_base::seekdir dir);

设置当前关联 streambuf 对象的输入位置指示器,失败的情况下调用 setstate(std::ios_base::failbit) 。

进行任何其他动作前, seekg 清除 eofbit

(C++11 起)

seekg 表现为无格式输入函数 (UnformattedInputFunction) ,除了不影响 gcount() 。构造并检查 sentry 对象后,

1) 设置输入位置指示器为绝对(相对于文件起始)值 pos 。具体而言,执行 rdbuf()->pubseekpos(pos, std::ios_base::in) 。

2) 设置输入位置指示器为相对于 dir 所定义位置的 off 。具体而言,执行 rdbuf()->pubseekoff(off, dir, std::ios_base::in) 。

参数

pos - 设置输入位置指示器到的绝对位置。
off - 设置输入位置指示器到的相对位置。
dir - 定义应用相对偏移到的基位置。它能为下列常量之一:
常量 解释
beg 流的开始
end 流的结尾
cur 流位置指示器的当前位置

返回值

*this

异常

若出现错误(错误状态标志不是 goodbit )并且设置了 exceptions() 为对该状态抛出则为 failure 。

若内部操作抛出异常,则捕获它并设置 badbit 。若对 badbit 设置了 exceptions() ,则重抛该异常。

调用示例

#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';
    return 0;
}

输出

猜你喜欢

转载自blog.csdn.net/qq_40788199/article/details/131735930