sstream —— string流中讀寫數據

sstream 頭文件定義的三個類型來支持IO操作。

  • istringstream :從string中讀取數據
  • ostringstream :向string中寫入數據
  • stringstream:即可以從string 中讀取數據,也可以向其中寫入數據。

sstream的一些特有操作

// ssm01是一個未綁定的stringstream對象
stringstream ssm01;
// ssm02是一個stringstream對象,保存字符串 s 的一個拷貝
stringstream ssm02(s);

// 返回ssm02所保存的string字符串的拷貝
ssm02.str();
// 將字符串 s 拷貝到ssm01中,返回void
ssm01.str(s);

一、istringstream 讀取string流

1、>> 方式讀取

該方法將字符串中的數據讀取,忽略所有空格。

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	string str01 = { " hello this @ just a test!  @ # && thanks " };
	istringstream ism(str01);
	string tmp;
	
	while (ism>>tmp)
	{
		cout << tmp << endl;
	}
	
	system("pause");
	return 0;
}

在這裏插入圖片描述

2、getline() 方式讀取

該方式會將所有空格讀取,其默認的分隔符是換行符號\n,可以自行設定分隔符
(1)、默認換行符爲分割符

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	string str01 = { " hello this @ just a test!  @ # && thanks \nu some one is here" };
	istringstream ism(str01);
	string tmp;
	
	while (getline(ism,tmp))
	{
		cout << tmp << endl;
	}
	
	system("pause");
	return 0;
}

在這裏插入圖片描述
(2)、當自行設定分割符爲@時,它會按照此字符來進行分割,但是當遇到換行符\n時,也會作爲分割依據。

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	string str01 = { " hello this @ just a test!  @ # && thanks \nu some one is here" };
	istringstream ism(str01);
	string tmp;
	
	while (getline(ism,tmp,'@'))
	{
		cout << tmp << endl;
	}
	
	system("pause");
	return 0;
}

在這裏插入圖片描述


二、ostringstream 向string流寫入數據

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	string str01 = "hello,,here,is";
	string str02 = "thanks for this! ";
	 // 創建ostringstream對象時綁定到指定字符串
	ostringstream osm01(str01);
	// 創建空對象,然後再輸出到該對象
	ostringstream osm02;
	osm02 << str02;

	string res01 = osm01.str(); //將osm01中所保存的string字符串賦給str02
	string res02 = osm02.str();
	
	cout << "res01= " << res01 << endl;
	cout << "str02= " << res02 << endl;

	system("pause");
	return 0;
}

在這裏插入圖片描述


三、stringstream 向string中讀寫數據

1、用於不同數據類型間的轉換
#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	stringstream ssm;
	int num, num01 = 10;
	string str, str01 = "666";

	//將變量num1從int 類型轉換成 string 類型
	ssm << num01; //向string流寫入數據
	ssm >> str; // 向string流讀取數據
	cout << "str= " << str << endl;

	ssm.clear();//清除流中的數據

	// 將變量str01從string 類型轉換成int類型
	ssm << str01;
	ssm >> num;
	cout << "num= " << num << endl;

	system("pause");
	return 0;
}

在這裏插入圖片描述

2、用於多string流集中輸出
#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main()
{
	stringstream ssm;
	ssm << "hello " << "this is";
	ssm << " some";
	ssm << " @1234";

	cout << ssm.str() << endl;

	system("pause");
	return 0;
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章