名前空間
変種
操作

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,

               conststd::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 として動作します。 sentry オブジェクトの構築および確認の後、出力書式のパディングが以下のように決定されます。

a) str.size()os.width() より小さくなければ、範囲 [str.begin(), str.end()) をそのまま使用します。
b) そうでなく、 (os.flags()& ios_base::adjustfield)== ios_base::left であれば、文字シーケンスの後に os.fill() 文字のコピーを os.width()-str.size() 個置きます。
c) そうでなければ、文字シーケンスの前に os.fill() 文字のコピーを os.width()-str.size() 個置きます。

その後、 os.rdbuf()->sputn(seq, std::max(os.width(), str.size())) によって行われるかのように、結果の文字シーケンス (str の内容 + パディング) から各文字が出力ストリーム os に格納されます。

最後に、 std::setw の効果 (もしあれば) を取り消すために、 os.width(0) を呼びます。

2) FormattedInputFunction として動作します。 sentry オブジェクトの構築および確認 (先頭のホワイトスペースをスキップするかもしれない) の後、まず strstr.erase() でクリアし、そして以下の条件のいずれかが真となるまで、 is から文字を読み込み、それを str.append(1, c) で行われたかのように str に追加します。

  • N 個の文字が読み込まれる。 ただし、 is.width() > 0 の場合 Nis.width()、そうでなければ Nstr.max_size() です。
  • ストリーム is で end-of-file の条件が発生する。
  • is 内の次の文字 c に対して std::isspace(c,is.getloc()) が真となる (このホワイトスペース文字は入力ストリームに残されます)。

1文字も抽出されなければ isstd::ios::failbit が設定されます。 これは std::ios_base::failure を投げる場合があります。

最後に、 std::setw の効果 (もしあれば) を取り消すために、 os.width(0) を呼びます。

目次

[編集]例外

1) 出力中に例外が投げられた場合、 std::ios_base::failure を投げるかもしれません。

2) is から1文字も抽出されない場合 (例えばストリームがファイルの終端であるとか、ホワイトスペースのみで構成されるとか)、または入力中に例外が投げられた場合、 std::ios_base::failure を投げるかもしれません。

[編集]引数

os - 文字出力ストリーム
is - 文字入力ストリーム
str - 挿入元または抽出先の文字列

[編集]戻り値

1) os

2) is

[編集]

#include <iostream>#include <string>#include <sstream>   int main(){std::string greeting ="Hello, whirled!";std::istringstream is(greeting);   std::string hello_comma;std::string whirled;   is >> hello_comma; is >> whirled;   std::cout<< greeting <<'\n';std::cout<< hello_comma <<'\n'<< whirled <<'\n';}

出力:

Hello, whirled! Hello, whirled!
close