std::basic_istream<CharT,Traits>::get
來自 cppreference.com
< cpp | io | basic istream
int_type get(); |
(1) | |
basic_istream& get( char_type& ch ); |
(2) | |
basic_istream& get( char_type* s, std::streamsize count ); |
(3) | |
basic_istream& get( char_type* s, std::streamsize count, char_type delim ); |
(4) | |
basic_istream& get( basic_streambuf& strbuf ); |
(5) | |
basic_istream& get( basic_streambuf& strbuf, char_type delim ); |
(6) | |
從流中提取字元。
所有版本都作為UnformattedInputFunctions行為。在構造並檢查哨兵物件後,這些函式執行以下操作:
2) 讀取一個字元並將其儲存到ch(如果可用)。否則,保持ch不變,並設定failbit和eofbit。請注意,與格式化字元輸入運算子>>不同,此函式未對型別signed char和unsigned char進行過載。
4) 讀取字元並將它們儲存到由s指向的字元陣列的連續位置。提取並存儲字元直到發生以下任何情況:
- count小於1或已儲存count - 1個字元。
- 輸入序列中發生檔案結束條件(呼叫setstate(eofbit))。
- 下一個可用輸入字元c等於delim,由Traits::eq(c, delim)確定。此字元未被提取(與
getline()
不同)。
在任何情況下,如果count > 0,則在陣列的下一個連續位置儲存一個空字元(CharT())。
6) 讀取字元並將它們插入到由給定的basic_streambuf物件控制的輸出序列中。提取並插入字元到strbuf中,直到發生以下任何情況:
- 輸入序列中發生檔案結束條件。
- 插入到輸出序列失敗(在這種情況下,無法插入的字元未被提取)。
- 下一個可用輸入字元c等於delim,由Traits::eq(c, delim)確定。此字元未被提取。
- 發生異常(在這種情況下,異常被捕獲而不重新丟擲)。
如果沒有提取任何字元,則呼叫setstate(failbit)。
所有版本都將gcount()的值設定為已提取的字元數。
目錄 |
[編輯] 引數
ch | - | 指向要寫入結果的字元的引用 |
s | - | 指向用於儲存字元的字元字串的指標 |
count | - | 由s指向的字元字串的大小 |
delim | - | 用於停止提取的分隔字元。它既不被提取也不被儲存 |
strbuf | - | 用於讀取內容的流緩衝區 |
[編輯] 返回值
1) 提取的字元或Traits::eof()。
2-6) *this
[編輯] 異常
如果內部操作丟擲異常,則會捕獲該異常並設定badbit。如果exceptions()設定為針對badbit
丟擲,則會重新丟擲該異常。
[編輯] 示例
執行此程式碼
#include <iostream> #include <sstream> int main() { std::istringstream s1("Hello, world."); char c1 = s1.get(); // reads 'H' std::cout << "after reading " << c1 << ", gcount() == " << s1.gcount() << '\n'; char c2; s1.get(c2); // reads 'e' char str[5]; s1.get(str, 5); // reads "llo," std::cout << "after reading " << str << ", gcount() == " << s1.gcount() << '\n'; std::cout << c1 << c2 << str; s1.get(*std::cout.rdbuf()); // reads the rest, not including '\n' std::cout << "\nAfter the last get(), gcount() == " << s1.gcount() << '\n'; }
輸出
after reading H, gcount() == 1 after reading llo,, gcount() == 4 Hello, world. After the last get(), gcount() == 7
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 370 | C++98 | 過載(5)的效果是get(s, count, widen('\n')), 這是過載(3)的效果 |
更正為 get(strbuf, widen('\n')) |
LWG 531 | C++98 | 過載(3,4)無法處理 count為非正數的情況 |
在這種情況下不提取任何字元。 未提取任何字元 |
[編輯] 另請參閱
提取字元塊 (公共成員函式) | |
提取格式化資料 (公共成員函式) | |
提取字元和字元陣列 (函式模板) |