4. Stringstream

在C語言的時候處理字串非常麻煩,而且在輸入字串的時候要使用char[]或char*,很不直觀,到了C++的時候多了string這個資料型態,在C++11的時候又有了stringstream,此時要做字串處理變得很方便。
要使用stringstream前要先引用一個標頭檔,#include <sstream>,stringstream專門拿來讀取字串並且處理。

1. int 轉換成 string

#include <iostream> #include <sstream> using namespace std; int main(){ stringstream ss; string int_to_str; int num = 12345; ss << num; ss >> int_to_str; cout << int_to_str << endl; return 0; }

2. string 轉換成 int

#include <iostream> #include <sstream> using namespace std; int main(){ stringstream ss; string int_to_str = "11804"; int num; ss << int_to_str; ss >> num; cout << num << endl; return 0; }

3. 清除stringstream

如果使用過的stringstream還要繼續使用,必須先清除,如果未清除則會出現無法預測的答案,以下為未清除的時候。

#include <iostream> #include <sstream> using namespace std; int main(){ stringstream ss; string int_to_str = "11804"; int num; ss << int_to_str; ss >> num; cout << num << " "; string str = "12345"; ss << str; int a; ss >> a; cout << a ; return 0; }

此時的輸出是:11804 0
但我們希望的結果為11804 12345
所以我們要進行刪除,利用ss.str(""); ss.clear();。

#include <iostream> #include <sstream> using namespace std; int main(){ stringstream ss; string int_to_str = "11804"; int num; ss << int_to_str; ss >> num; cout << num << " "; ss.str(""); ss.clear(); string str = "12345"; ss << str; int a; ss >> a; cout << a; return 0; }

此時就可以正常輸出了。

4. 利用stringstream進行基本輸出

#include <iostream> #include <sstream> using namespace std; int main(){ stringstream ss1("he"); stringstream ss2,ss3,ss4; string str("max"); ss2.str("hello"); ss3.str(str); ss4 << "hey"; cout << ss1.str() << endl;//output = he cout << ss2.str() << endl;//output = hello cout << ss3.str() << endl;//output = max cout << ss4.str() << endl;//output = hey return 0; }

5. 分割stringstream

用空格做切割

#include <iostream> #include <sstream> using namespace std; int main(){ stringstream ss1("my name is max "); string str(""); while(ss1 >> str) cout << str << endl; return 0; }

用getline()把stringstream用特定的string取出

第一個arguement放stringstream,第二個arguement放string,第三個arguement只能放char,不能放string。

#include <iostream> #include <sstream> using namespace std; int main(){ stringstream ss("hello my name is max"); string str; while(getline(ss,str,'m')){ cout << str << endl; } return 0; }

output :
hello
y na
e is
ax