# C++對於字符串引入了ostringstream、istringstream、stringstream三個類,
使用時需要包含<sstream>這個頭文件。
* ostringstream類:用於執行C風格的串流的輸出操作。
* strstream類:同時可以支持C風格的串流的輸入輸出操作。
* istringstream的構造函數原形:istringstream::istringstream(string str);
.它的作用是從string對象str中讀取字符。
# 字符串流存放在內存裏,操作速度快。
Demo:
#include <iostream>
#include <sstream> //字符串流
/*字符串流在內存裏,速度快*/
using namespace std;
int main()
{
cout << "將數據輸入到字符串流...\n";
ostringstream osstream;
osstream << "姓名: " << "douBi" << "\n" //必須加空格來區分字符串,這裏在'姓名'後了加空格
<< "年齡: " << 22 << "\n"
<< "體重: " << 88.8 << "\n";
cout << "將內存中的字符流讀出:\n" << osstream.str();
cout << endl << "讀取內存中的字符流:" << endl;
string dump; //丟棄的數據
string name;
int age;
double weight;
istringstream isstream(osstream.str());
isstream >> dump; //丟棄 姓名
cout << "dump: " << dump << endl;
isstream >> name;
isstream >> dump;
cout << "dump: " << dump << endl;
isstream >> age;
isstream >> dump;
cout << "dump: " << dump << endl;
isstream >> weight;
cout << name << endl;
cout << age << endl;
cout << weight << endl;
return 0;
}
輸出: