首页 > 技术文章 > stringstream

Anber82 2019-08-13 21:48 原文

stringstream是用于C++风格的字符串的输入输出的。同时可以支持C风格的串流的输入输出操作。

作用:

  一般用于格式转换。把数字字符转为整数数字。

初始化方法:

1.

stringstream stream;
int a;
stream << "12";
stream >> a;
cout << a << endl;

2.

stringstream stream("adfaf afagfagag");
string a;
stream >> a;
cout << a << endl;

3.

string a = "aljfljfalf";
stringstream stream(a);
cout << stream.str() << endl;

案例实现:

 1 #include <iostream>
 2 #include <sstream>
 3 using namespace std;
 4 int main()
 5 {
 6     stringstream stream;
 7     int a,b;
 8     stream << "080";//将“080”写入到stream流对象中
 9     stream >> a;//将stream流写入到a中,并根据a的类型进行自动转换,"080" -> 80
10     cout << stream.str() << endl;//成员函数str()返回一个string对象,输出80
11     cout << stream.length() << endl;//2
12     return 0;
13 }

 

 1 #include <iostream>
 2 #include <sstream>
 3 using namespace std;
 4 int main()
 5 {
 6     stringstream stream("123 3.14 hello");//不同对象用空格隔开,默认根据空格进行划分  
 7     double a;
 8     double b;
 9     string c;
10     //将对应位置的内容提取出来写到对应的变量中
11     //如果类型不同,自动转换
12     stream >> a >> b >> c;//输出 1233.14hello
13     cout << a << b << c;
14     stream.clear();
15     return 0;
16 }

stream用完之后,其内存和标记仍然存在,需要用两个函数来初始化。

clear()只是清空该流的错误标记,并没有清空stream流(没有清空内存);

str()是给stream内容重新赋值为空。

一般clear和str()结合起来一起用。

 1 #include <iostream>
 2 #include <sstream>
 3 #include <cstdlib>//用于system("PAUSE")
 4 using namespace std;
 5 int main()
 6 {
 7     stringstream stream;
 8     int a,b;
 9     stream << "80";
10     stream >> a;
11     cout << stream.str() << endl;//此时stream对象内容是"80",不是空的
12     cout << stream.str().length() << endl;//此时内存为2byte
13     
14     //此时再将新的"90"写入进去的话,会出错的,因为stream重复使用时,没有清空会导致错误。
15     //如下:
16     stream << "90";
17     stream >> b;
18     cout << stream.str() << endl;//还是80
19     cout << b << endl;//1752248,错了,没有清空标记,给了b一个错误的数值
20     cout << stream.str().length() << endl;//还是2bytes
21     
22     //如果只用stream.clear(),只清空了错误标记,没有清空内存
23     stream.clear();
24     stream << "90";
25     stream >> b;
26     cout << b << endl;//90
27     cout << stream.str() <<endl;//变成90
28     cout << stream.str().length() << endl;//4,因为内存没有释放,2+2 = 4bytes
29     
30     //stream.clear() 和 stream.str("")都使用,标记和内存都清空了
31     stream << "90";
32     stream >> b;
33     cout << b << endl;
34     cout << stream.str() << endl;//90
35     cout << stream.str().length() << endl;//2bytes
36     
37     system("PAUSE");
38     return 0;
39 }

参考:

https://www.cnblogs.com/pacino12134/p/11033022.html#top

推荐阅读