stringstream类的简介和用法

一、简介

 <sstream>类库定义了三种类:istringstream,ostringstream,stringstream.分别用来进行流的输入,流的输出,输入输出操作.在此演示stringstream的使用.**stringstream最大的特点是可以很方便的实现各种数据类型的转换,不需要像C语言中转换那么麻烦,而且转换非常安全.所以stringstream经常用于方便安全的类型转换.

二、用法

(1)数据的分割(string --> string)

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<sstream>
 4 using namespace std;
 5 
 6 string str[100];
 7 
 8 int main()
 9 {
10     string line;
11     int cnt = 0;
12     while (getline(cin, line))        //每次取一行
13     {
14         stringstream ss(line);        //将字符串根据空格分隔成一个个单词
15         while (ss >> str[cnt])
16         {
17             cout << str[cnt++] << " ";
18         }
19     }
20     return 0;
21 }

(2)数据的拼接

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<sstream>
 4 using namespace std;
 5 
 6 int main()
 7 {
 8     stringstream ss;
 9     int num1 = 12345;
10     int num2 = 6789;
11     string str2 = "abc";
12     string str;
13     ss << num1;
14     ss << num2;
15     ss << str2;
16     ss >> str;
17     cout << str;        //可以不同类型拼接,输出123456789abc
18 
19     return 0;
20 }

(3)数据类型的转换

 1 #include<stdio.h>
 2 #include<iostream>
 3 #include<sstream>
 4 using namespace std;
 5 
 6 template<class T>
 7 void Tostring(string &result, const T &t)    //用模板将各种数值转化成string类型 
 8 {
 9     stringstream ss;
10     ss << t;
11     ss >> result;            
12 }
13 
14 int main()
15 {
16     stringstream ss;
17     string str;
18     string str2 = "1122334455a123";
19     int num1 = 12345;
20     float num2 = 3.1415926;
21     char arr[100];
22 
23     Tostring(str, num2);
24     cout << str << endl;
25 
26     ss.clear();                    
27     ss.str("");                    //在另外一篇blog有解释
28     ss << num1;
29     ss >> str;
30     cout << str << endl;        //int --> string,输出12345
31 
32     ss.clear();
33     ss.str("");
34     ss << num2;
35     ss >> str;
36     cout << str << endl;        //float --> string,输出3.14159,好像小数点5位之后的会丢掉
37 
38     ss.clear();
39     ss.str("");
40     ss << str2;
41     ss >> num1;                    //string --> int,输出1122334455,遇到非数字会停止
42     cout << num1 << endl;
43 
44     ss.clear();
45     ss.str("");
46     ss << str2;
47     ss >> num2;                    //string --> float,输出1122334455,遇到非数字也会停止
48     cout << num1 << endl;
49 
50     ss.clear();
51     ss.str("");
52     ss << str2;
53     ss >> arr;                    //string --> char*,输出1 3,转换成其他类型数组不行
54     cout << arr[0] <<" "<< arr[5] << endl;
55 
56     return 0;
57 }
原文地址:https://www.cnblogs.com/lfri/p/9363401.html