Stringstream
在C語言的時候處理字串非常麻煩,而且在輸入字串的時候要使用char[]或char*,很不直觀,到了C++的時候多了string這個資料型態,在C++11的時候又有了stringstream,此時要做字串處理變得很方便。
要使用stringstream前要先引用一個標頭檔,#include
<sstream>,stringstream專門拿來讀取字串並且處理。 ## 1. int 轉換成
string 1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}1
2
3
4
5
6
7
8
9
10
11
12
13
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;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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;
}1
2
3
4
5
6
7
8
9
10
11
using namespace std;
int main(){
stringstream ss1("my name is max ");
string str("");
while(ss1 >> str)
cout << str << endl;
return 0;
}1
2
3
4
5
6
7
8
9
10
11
12
using namespace std;
int main(){
stringstream ss("hello my name is max");
string str;
while(getline(ss,str,'m')){
cout << str << endl;
}
return 0;
}