简介

<sstream>库定义了三种类:istringstream、ostringstream 和 stringstream,分别用来进行流的输入、输出和输入输出操作。简单起见,我主要以 stringstream 为重点,讲讲这个STL

简单类型转换 string To int

1
2
3
4
5
6
7
8
9

string result=”10000”;

int n=0;

stream<<result;

stream>>n;  //n等于10000

定义一个通用的类型转换模板

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19

template<typename out_type,typename in_value>

out_type convert(const in_value & t)

{

    stringstream stream; 

    stream<<t;//向流中传值

    out_type result;//这里存储转换结果

    stream>>result;//向result中写入值

    return result;

}

hdu2072实践

统计一篇文章中出现的不同单词的个数,文章由小写字母和空格构成

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

#include <iostream>

#include <set>

#include <sstream>

using namespace std;

set<string> temp;

string row,input;

int main() {

    while(getline(cin, row)&&row!="#")  //输入一行字符串可以用getline

    {

        temp.clear();

        stringstream str(row); 

        while(str>>input) //输出str中的单词以空格隔开 

            temp.insert(input);

        cout<<temp.size()<<endl;

    }

    return 0;

}

结论

sstream老好用了