stringstream

1、stringstream的基本操作

#include<bits/stdc++.h>
using namespace std;
int main() {
	string s = "123";
	stringstream ss(s);//s作爲初值
	string t = ss.str();
	//ss.str()返回一個臨時的string,函數執行完以後將被析構
	//不能用此臨時string進行別的操作,可以先將這個值賦值給別的string再進行操作
	//此值可以直接賦值或者直接輸出
	cout << t << endl;
}

2、stringstream經常用來類型轉換

#include<bits/stdc++.h>
using namespace std;
int main() {
	//string轉int
	stringstream ss;
	string s="123";
	int x;
	ss << s;
	ss >> x;
	cout << x << endl;
}
#include<bits/stdc++.h>
using namespace std;
int main() {
	//int到string
	stringstream ss;
	string s;
	int x=123;
	ss << x;
	ss >> s;
	cout << s << endl;
}

3、stringstream用來分割字符,可以分割空格,回車,tab隔開的

#include<bits/stdc++.h>
using namespace std;
int main() {
	//int到string
	stringstream ss;
	string s;
	getline(cin, s);
	ss << s;
	string t;
	while (ss >> t) {
		cout << t << endl;
	}
}

4、string不能重用,重用時需要用clear清空緩存,不清空將會出錯

#include<bits/stdc++.h>
using namespace std;
int main() {
	stringstream ss;
	string s="123";
	int x;
	ss << s;
	ss >> x;
	cout << x << endl << endl;

	ss.clear();

	bool b = true;
	ss << b;
	ss >> x;
	cout << x;
}

5、ss.clear()和ss.str("")的區別

ss.clear()可以清空緩存,重用的時候使用,不能清空內存,會導致內存越來越大

ss.str("")用來清空內存

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