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

出自cppreference.com


 
 
 
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) 。構造並檢查哨兵對象後,確定輸出格式填充

然後將結果序列的每個字符(str 的內容加上填充)插入到輸出流 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 個字符,其中如果 is.width() > 0,那麼 Nis.width(),否則 Nstr.max_size()
  • is 中出現文件尾條件,或者
  • std::isspace(c, is.getloc())is 中的下個字符 ctrue(空白符留在輸入流中)。

如果沒有提取任何字符,那麼設置 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';
    
    // 重置流
    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()) 被用來檢查
空白字符,但 <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)

參閱

進行字符串視圖的流輸出
(函數模板) [編輯]