std::basic_istream<CharT,Traits>::seekg
來自 cppreference.com
< cpp | io | basic istream
basic_istream& seekg( pos_type pos ); |
(1) | |
basic_istream& seekg( off_type off, std::ios_base::seekdir dir ); |
(2) | |
設定當前關聯的 streambuf
物件的輸入位置指示器。
在執行任何其他操作之前,seekg 會清除 eofbit 。 |
(C++11 起) |
seekg
的行為類似於 非格式化輸入函式,除了 gcount() 不受影響。在構造並檢查哨兵物件後,
1) 如果 fail() != true,將輸入位置指示器設定為絕對值(相對於檔案開頭)pos。具體來說,執行 rdbuf()->pubseekpos(pos, std::ios_base::in)(pubseekpos 又會呼叫特定緩衝區的 seekpos,例如 basic_filebuf::seekpos、basic_stringbuf::seekpos 或 strstreambuf::seekpos)。如果失敗,則呼叫 setstate(std::ios_base::failbit)。
2) 如果 fail() != true,將輸入位置指示器設定為相對於 dir 定義的位置的 off 位置。具體來說,執行 rdbuf()->pubseekoff(off, dir, std::ios_base::in)。如果失敗,則呼叫 setstate(std::ios_base::failbit)。
目錄 |
[編輯] 引數
pos | - | 要設定輸入位置指示器的絕對位置 | ||||||||
off | - | 要設定輸入位置指示器的相對位置(正或負) | ||||||||
dir | - | 定義應用相對偏移量的基本位置。它可以是以下常量之一
|
[編輯] 返回值
*this
[編輯] 異常
如果內部操作丟擲異常,則捕獲該異常並設定 badbit。如果 exceptions() 設定為針對 badbit
丟擲異常,則重新丟擲該異常。
[編輯] 注意
seekg(n) 不一定等同於 seekg(n, ios::beg)。例如,std::basic_ifstream 要求絕對位置 n 來自 tellg()。
[編輯] 示例
執行此程式碼
#include <iostream> #include <sstream> #include <string> int main() { std::string str = "Hello, world"; std::istringstream in(str); std::string word1, word2; in >> word1; in.seekg(0); // rewind in >> word2; std::cout << "word1 = " << word1 << '\n' << "word2 = " << word2 << '\n'; }
輸出
word1 = Hello, word2 = Hello,
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 129 | C++98 | 無法指示失敗 | 失敗時設定 failbit |
LWG 136 | C++98 | seekg 可以設定輸出流 |
只設置輸入流 |
LWG 537 | C++98 | off 的型別是 off_type& |
更正為 off_type |
[編輯] 另請參閱
返回輸入位置指示符 (公共成員函式) | |
返回輸出位置指示器 ( std::basic_ostream<CharT,Traits> 的公共成員函式) | |
設定輸出位置指示器 ( std::basic_ostream<CharT,Traits> 的公共成員函式) | |
呼叫 seekpos() ( std::basic_streambuf<CharT,Traits> 的公共成員函式) | |
[虛擬函式] |
使用絕對地址重新定位檔案位置 ( std::basic_filebuf<CharT,Traits> 的虛保護成員函式) |
[虛擬函式] |
使用絕對定址重新定位輸入序列、輸出序列或兩者的下一個指標 ( std::basic_stringbuf<CharT,Traits,Allocator> 的虛保護成員函式) |
[虛擬函式] |
使用絕對定址重新定位輸入序列、輸出序列或兩者的下一個指標 ( std::strstreambuf 的虛保護成員函式) |
呼叫 seekoff() ( std::basic_streambuf<CharT,Traits> 的公共成員函式) | |
[虛擬函式] |
使用相對地址重新定位檔案位置 ( std::basic_filebuf<CharT,Traits> 的虛保護成員函式) |
[虛擬函式] |
使用相對定址重新定位輸入序列、輸出序列或兩者的下一個指標 ( std::basic_stringbuf<CharT,Traits,Allocator> 的虛保護成員函式) |
[虛擬函式] |
使用相對定址重新定位輸入序列、輸出序列或兩者的下一個指標 ( std::strstreambuf 的虛保護成員函式) |