C / C ++スタディノート12の入力と出力(I / O)(3)

文字列のストリーム

1。概要

        これまでに見たすべてのI/Oの例は、coutへの書き込みまたはcinの読み取りです。ただし、文字列ストリームクラスと呼ばれる別のクラスのセットがあり、使い慣れた挿入(<<)および抽出(>>)演算子で文字列を操作できます。istreamやostreamと同様に、文字列ストリームはデータを保持するためのバッファを提供します。ただし、cinやcoutとは異なり、これらのストリームはI / Oチャネル(キーボード、モニターなど)に接続されていません。文字列ストリームの主な用途の1つは、後で表示するために出力をバッファリングすること、または入力を1行ずつ処理することです。

        文字列には6つのストリームクラスがあります。通常の文字幅の文字列を読み書きするためのistringstream(istreamから派生)、ostringstream(ostreamから派生)、およびstringstream(iostreamから派生)です。wistringstream、wostringstream、およびwstringstreamは、幅の広い文字列の読み取りと書き込みに使用されます。文字列ストリームを使用するには、sstreamヘッダーを#includeする必要があります。

1、stringstream

        データを文字列ストリームに入れる方法は2つあります。

        1.挿入(<<)演算子を使用します。

std::stringstream os;
os << "en garde!" << '\n'; // insert "en garde!" into the stringstream

        2. str(string)関数を使用して、バッファーの値を設定します。

std::stringstream os;
os.str("en garde!"); // set the stringstream buffer to "en garde!"

        文字列ストリームからデータを取得する方法も2つあります。

        1. str()関数を使用して、バッファーの結果を取得します。

std::stringstream os;
os << "12345 67.89" << '\n';
std::cout << os.str();

//输出
12345 67.89

        2.抽出(>>)演算子を使用します。

std::stringstream os;
os << "12345 67.89"; // insert a string of numbers into the stream

std::string strValue;
os >> strValue;

std::string strValue2;
os >> strValue2;

// print the numbers separated by a dash
std::cout << strValue << " - " << strValue2 << '\n';


//输出
12345 - 67.89

        >>演算子は文字列を反復処理することに注意してください。>>を連続して使用するたびに、ストリーム内の次の抽出可能な値が返されます。一方、str()は、ストリームで>>が使用されている場合でも、ストリームの値全体を返します。

2.文字列と数値の間の変換

        挿入演算子と抽出演算子はすべての基本的なデータ型を処理する方法を知っているため、それらを使用して文字列を数値に変換したり、その逆を行ったりすることができます。

        まず、数値を文字列に変換する方法を見てみましょう。

std::stringstream os;

int nValue{ 12345 };
double dValue{ 67.89 };
os << nValue << ' ' << dValue;

std::string strValue1, strValue2;
os >> strValue1 >> strValue2;

std::cout << strValue1 << ' ' << strValue2 << '\n';

//输出

12345 67.89

        次に、数値文字列を数値に変換しましょう。

std::stringstream os;
os << "12345 67.89"; // insert a string of numbers into the stream
int nValue;
double dValue;

os >> nValue >> dValue;

std::cout << nValue << ' ' << dValue << '\n';

//输出
12345 67.89

        文字列ストリームのバッファを空にする方法はいくつかあります。

        1.空のCスタイルの文字列でstr()を使用して、空の文字列に設定します。

std::stringstream os;
os << "Hello ";

os.str(""); // erase the buffer

os << "World!";
std::cout << os.str();

        2.空白のstd::stringオブジェクトでstr()を使用して、空の文字列に設定します。

std::stringstream os;
os << "Hello ";

os.str(std::string{}); // erase the buffer

os << "World!";
std::cout << os.str();

        どちらのプログラムでも、次の結果が得られます。

World!

        文字列ストリームをクリアするときは、clear()関数を呼び出します。

std::stringstream os;
os << "Hello ";

os.str(""); // erase the buffer
os.clear(); // reset error flags

os << "World!";
std::cout << os.str();

        clear()は、設定されている可能性のあるエラーフラグをリセットし、ストリームを通常の状態に戻します。次のレッスンでは、ストリームの状態とエラーフラグについて詳しく説明します。

おすすめ

転載: blog.csdn.net/bashendixie5/article/details/125027427