operator<<,>>(std::basic_string)
出自cppreference.com
| 在標頭 <string> 定義
|
||
| |
(1) | |
| |
(2) | |
1) 表現為有格式輸出函數 (FormattedOutputFunction) 。構造並檢查哨兵對象後,確定輸出格式填充。
然後將結果序列的每個字符(str 的內容加上填充)插入到輸出流 os,如同通過調用 os.rdbuf()->sputn(seq, n),其中 n 是 std::max(os.width(), str.size())。
最後,調用 os.width(0) 以取消 std::setw 的效果,如果存在。
|
等價於 |
(C++17 起) |
2) 表現為有格式輸入函數 (FormattedInputFunction) 。構造並檢查哨兵對象,這可能會跳過前導空白符,然後首先以
str.erase() 清除 str,再從 is 讀取字符並後附它們到 str,如同用 str.append(1, c),直到滿足下列��一條件:
- 讀取了
N個字符,其中如果is.width() > 0,那麼N是is.width(),否則N是str.max_size(), - 流
is中出現文件尾條件,或者 std::isspace(c, is.getloc())對is中的下個字符c是true(空白符留在輸入流中)。
如果沒有提取任何字符,那麼設置 is 上的 std::ios::failbit,這可能會拋出 std::ios_base::failure。
is.width(0) 以取消 std::setw 的效果,如果存在。 異常
1) 如果在輸出中拋出異常,那麼可能會拋出 std::ios_base::failure。
2) 如果沒有從
is 中提取任何字符(例如流在文件尾或僅有空白符組成),或在輸入中拋出異常,那麼可能會拋出 std::ios_base::failure。參數
| os | - | 字符輸出流 |
| is | - | 字符輸入流 |
| str | - | 插入或提取的字符串 |
返回值
1)
os2)
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';
// 重置流
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()) 被用來檢查空白字符,但 <string> 中沒有聲明 getloc
|
將 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 問題 25 的解決方案導致 os.width() 大於 str.size() 時的行為未定義
|
先確定填充,並改成 插入填充後的字符序列 |
| LWG 586 | C++98 | operator<< 沒有表現為有格式輸出函數 (FormattedOutputFunction) |
表現為 有格式輸出函數 (FormattedOutputFunction) |
參閱
(C++17) |
進行字符串視圖的流輸出 (函數模板) |