operator<<,>>(std::basic_string)
來自 cppreference.com
< cpp | string | basic_string
定義於標頭檔案 <string> |
||
template< class CharT, class Traits, class Allocator > std::basic_ostream<CharT, Traits>& |
(1) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT, Traits>& |
(2) | |
1) 行為如同一個 FormattedOutputFunction。在構造並檢查哨兵物件後,確定輸出格式填充。
然後將結果序列 seq(str 的內容加填充)中的每個字元插入到輸出流 os,如同呼叫 os.rdbuf()->sputn(seq, n),其中 n 是 std::max(os.width(), str.size())。最後,呼叫 os.width(0) 以取消 std::setw(如果有)的效果。
等價於 return os << std::basic_string_view<CharT, Traits>(str);。 |
(C++17 起) |
2) 行為如同一個 FormattedInputFunction。在構造並檢查哨兵物件(其可能跳過前導空白字元)後,首先用 str.erase() 清空 str,然後從 is 讀取字元並將其附加到 str,如同透過 str.append(1, c),直到以下條件之一變為真:
- 讀取了
N
個字元,其中N
是 is.width(),如果 is.width() > 0,否則N
是 str.max_size(), - 流 is 中發生檔案結束條件,或
- 對於 is 中的下一個字元 c,std::isspace(c, is.getloc()) 為 true(此空白字元保留在輸入流中)。
如果沒有提取任何字元,則在 is 上設定 std::ios::failbit,這可能丟擲 std::ios_base::failure。
最後,呼叫 is.width(0) 以取消 std::setw(如果有)的效果。目錄 |
[編輯] 異常
1) 如果在輸出期間丟擲異常,可能丟擲 std::ios_base::failure。
[編輯] 引數
os | - | 字元輸出流 |
is | - | 字元輸入流 |
str | - | 要插入或提取的字串 |
[編輯] 返回值
1) os
2) is
[編輯] 示例
執行此程式碼
#include <iostream> #include <sstream> #include <string> int main() { std::string greeting = "Hello, whirled!"; std::istringstream iss(greeting); std::string hello_comma, whirled, word; iss >> hello_comma; iss >> whirled; std::cout << greeting << '\n' << hello_comma << '\n' << whirled << '\n'; // Reset the stream iss.clear(); iss.seekg(0); while (iss >> word) std::cout << '+' << word << '\n'; }
輸出
Hello, whirled! Hello, whirled! +Hello, +whirled!
[編輯] 缺陷報告
下列更改行為的缺陷報告追溯地應用於以前出版的 C++ 標準。
缺陷報告 | 應用於 | 釋出時的行為 | 正確的行為 |
---|---|---|---|
LWG 25 | C++98 | n 是 os.width() 和 str.size() 中較小的一個 | n 是它們中較大的一個 |
LWG 90 | C++98 | 曾使用 std::isspace(c, getloc()) 檢查 空格,但 getloc 未在 <string> 中宣告 |
替換 getloc() 為 is.getloc() |
LWG 91 | C++98 | operator>> 未行為如同一個 FormattedInputFunction |
行為如同一個 FormattedInputFunction(格式化輸入函式) |
LWG 211 | C++98 | 如果未提取任何字元,operator>> 未設定 failbit |
設定 failbit |
LWG 435 | C++98 | 字元透過 os.rdbuf()->sputn(str.data(), n) 插入, 且 LWG issue 25 的解決方案使得該行為 未定義,如果 os.width() 大於 str.size() |
首先確定填充 並插入帶填充的 字元序列 |
LWG 586 | C++98 | operator<< 未行為如同一個 FormattedOutputFunction |
行為如同一個 FormattedOutputFunction(格式化輸出函式) |
[編輯] 另請參閱
(C++17) |
對 string_view 執行流輸出 (函式模板) |