stringstream的用法

stringstream概述

  • 頭文件:< sstream >
  • 繼承自:< iostream>
    在這裏插入圖片描述
  • 自身的成員函數:構造, rdbuf, str
  • str:將緩衝區中的數據以string的形式轉換。返回值爲string。
繼承的主要使用的成員函數
  • [>>]:繼承自istream,可以向sstream中輸入數據。
  • [<<]:可以向某些變量裏輸出數據。

具體應用

string 轉 int / double 這樣的類型轉化
void StrtoInt(string& str)
{
	stringstream ss;
	ss << str;
	//int num = ss.get();
	int num;
	ss >> num;
	cout << num * 2 << endl;
}

在這裏插入圖片描述

int / double 轉 string 這樣的類型轉化
void InttoStr(int num)
{
	stringstream ss;
	ss << num;
	string s;
	ss >> s;
	s.append("that is int to string");
	cout << s << endl;
}

在這裏插入圖片描述
這個操作的情況下,可以完成一些小的統計:從0到2020中9出現的數字有多少個?

int Func2()
{
	int num = 0;
	for (int i = 0; i < 2021; i++)
	{
		stringstream s;
		s << i;
		string str = s.str();
		if (str.find('9') != string::npos)
			num++;
	}
	return a;
}
多個字符串拼接
void StrJoin()
{
	string str1 = "hello ";
	string str2 = "world!";
	stringstream ss;
	ss << str1 << str2;
	cout << ss.str() << endl;
}

在這裏插入圖片描述

通過空格來拆分字符串
void StrSplit()
{
	string str = "hello world !";
	stringstream ss;
	ss << str;
	string s1, s2, s3;
	ss >> s1 >> s2 >> s3;
	cout << s1 << endl;
	cout << s2 << endl;
	cout << s3 << endl;
}

在這裏插入圖片描述

注意事項

stringstream的基本用法已經講完了,在進行一些數據轉化和數據分割的時候可以減少很多的時間。

  • 需要注意:stringstream所申請的對象需要每次使用完之後,需要進行清空,調用clear(),函數即可,因爲緩衝區內的數據還在緩衝區。如圖所示:
    在這裏插入圖片描述
    可以看到,ss中的數據並沒有因爲輸出到其他字符串中而消失,所以,一定要調用clear()進行清空。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章