最終更新日時(UTC):
が更新

履歴 編集

class template
<sstream>

std::basic_stringstream

namespace std {
  template <class CharT, class Traits = char_traits<CharT>,
            class Allocator = allocator<CharT> >
  class basic_stringstream : public basic_iostream<CharT, Traits>;

  using stringstream  = basic_stringstream<char>;
  using wstringstream = basic_stringstream<wchar_t>;
}

概要

バッファに保持された文字列への読み取りおよび書き込み操作ができるストリーム

メンバ関数

名前 説明 対応バージョン
(constructor) コンストラクタ
(destructor) デストラクタ
operator= ムーブ代入 C++11
swap 値の交換 C++11
rdbuf ストリームバッファオブジェクトの設定・取得
str 文字列オブジェクトの設定・取得
view 文字列ビューオブジェクトの取得 C++20

非メンバ関数

名前 説明 対応バージョン
swap 2つのオブジェクトを入れ替える C++11

メンバ型

名前 説明 対応バージョン
char_type テンプレート仮引数CharT
int_type Traits::int_type
pos_type Traits::pos_type
off_type Traits::off_type
traits_type テンプレート仮引数Traits
allocator_type テンプレート仮引数Allocator

#include <iostream>
#include <sstream>
#include <string>

int main()
{
  // 読み取りと書き込みが可能なストリーム
  std::stringstream ss;

  // データを書き込む
  ss << "Hello " << 123 << " World " << 45.67;

  // 文字列として取得
  std::cout << "Content: " << ss.str() << std::endl;

  // 読み取り位置をリセット
  ss.seekg(0);

  // データを読み取る
  std::string word1, word3;
  int num1;
  double num2;

  ss >> word1 >> num1 >> word3 >> num2;

  std::cout << "Read: word1=" << word1 
            << ", num1=" << num1 
            << ", word3=" << word3 
            << ", num2=" << num2 << std::endl;

  // 新しい内容でリセット
  ss.str("42 3.14159 test");
  ss.clear();  // エラーフラグをクリア

  int value;
  double pi;
  std::string text;
  ss >> value >> pi >> text;

  std::cout << "New data: " << value << ", " << pi << ", " << text << std::endl;
}

出力

Content: Hello 123 World 45.67
Read: word1=Hello, num1=123, word3=World, num2=45.67
New data: 42, 3.14159, test

参照