名稱空間
變體
操作

operator<<,>>(std::basic_string)

來自 cppreference.com
< cpp‎ | string‎ | basic_string
 
 
 
std::basic_string
 
定義於標頭檔案 <string>
template< class CharT, class Traits, class Allocator >

std::basic_ostream<CharT, Traits>&
    operator<<( std::basic_ostream<CharT, Traits>& os,

                const std::basic_string<CharT, Traits, Allocator>& str );
(1)
template< class CharT, class Traits, class Allocator >

std::basic_istream<CharT, Traits>&
    operator>>( std::basic_istream<CharT, Traits>& is,

                std::basic_string<CharT, Traits, Allocator>& str );
(2)
1) 行為如同一個 FormattedOutputFunction。在構造並檢查哨兵物件後,確定輸出格式填充

然後將結果序列 seqstr 的內容加填充)中的每個字元插入到輸出流 os,如同呼叫 os.rdbuf()->sputn(seq, n),其中 nstd::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 個字元,其中 Nis.width(),如果 is.width() > 0,否則 Nstr.max_size()
  • is 中發生檔案結束條件,或
  • 對於 is 中的下一個字元 cstd::isspace(c, is.getloc())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) 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 nos.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(格式化輸出函式)

[編輯] 另請參閱

對 string_view 執行流輸出
(函式模板) [編輯]