stringstream概述
- 头文件:< sstream >
- 继承自:< iostream>
- 自身的成员函数:构造, rdbuf, str
- str:将缓冲区中的数据以string的形式转换。返回值为string。
继承的主要使用的成员函数
- [>>]:继承自istream,可以向sstream中输入数据。
- [<<]:可以向某些变量里输出数据。
具体应用
string 转 int / double 这样的类型转化
void StrtoInt(string& str)
{
stringstream ss;
ss << str;
//int num = ss.get();
int num;
ss >> num;
cout << num * 2 << endl;
}
int / double 转 string 这样的类型转化
void InttoStr(int num)
{
stringstream ss;
ss << num;
string s;
ss >> s;
s.append("that is int to string");
cout << s << endl;
}
这个操作的情况下,可以完成一些小的统计:从0到2020中9出现的数字有多少个?
int Func2()
{
int num = 0;
for (int i = 0; i < 2021; i++)
{
stringstream s;
s << i;
string str = s.str();
if (str.find('9') != string::npos)
num++;
}
return a;
}
多个字符串拼接
void StrJoin()
{
string str1 = "hello ";
string str2 = "world!";
stringstream ss;
ss << str1 << str2;
cout << ss.str() << endl;
}
通过空格来拆分字符串
void StrSplit()
{
string str = "hello world !";
stringstream ss;
ss << str;
string s1, s2, s3;
ss >> s1 >> s2 >> s3;
cout << s1 << endl;
cout << s2 << endl;
cout << s3 << endl;
}
注意事项
stringstream的基本用法已经讲完了,在进行一些数据转化和数据分割的时候可以减少很多的时间。
- 需要注意:stringstream所申请的对象需要每次使用完之后,需要进行清空,调用clear(),函数即可,因为缓冲区内的数据还在缓冲区。如图所示:
可以看到,ss中的数据并没有因为输出到其他字符串中而消失,所以,一定要调用clear()进行清空。