題目很簡單。其實stringstream就的用法和iosteam差不多,所以學習起來是很簡單的。stringstream類里面有一個string緩存,str()和str(string)成員函數。
前者用于把stringstream的返回string緩存,后者是把string對象包裝成stringstream對象。stringstream類存在于sstream頭文件中。其是獨立于標準I/O但有類似
功能的類。clear主要是為了多次使用stringstream,因為stringstream每次的構造都十分耗時,所以最后能多次,反復使用,就如同面向對象里面的單例模式。
代碼如下:
1 #include <iostream>
2 #include <string>
3 #include <set>
4 #include <sstream>
5
6
7 using namespace std;
8
9 set<string> dict;
10 stringstream ss;
11
12 /*
13 主要學習兩個重點stringstream的用法與set容器的insert、迭代器的用法。
14 */
15 int main() {
16
17 string s,buf;
18
19 while (cin >> s) {
20 int len = s.size();
21 for (int i = 0; i < len; i++) {
22 if (isalpha(s[i])) s[i] = tolower(s[i]); else s[i] = ' ';
23 }
24 ss.clear();
25 ss.str(s);
26 while (ss >> buf) dict.insert(buf);
27 }
28
29 for (set<string>::iterator it = dict.begin(); it != dict.end(); ++it)
30 cout << *it << endl;
31 return 0;
32 }