当前位置:   article > 正文

stringstream的用法_stringstream >>

stringstream >>

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在这里插入图片描述

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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

在这里插入图片描述
这个操作的情况下,可以完成一些小的统计:从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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
多个字符串拼接
void StrJoin()
{
	string str1 = "hello ";
	string str2 = "world!";
	stringstream ss;
	ss << str1 << str2;
	cout << ss.str() << endl;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述

通过空格来拆分字符串
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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

注意事项

stringstream的基本用法已经讲完了,在进行一些数据转化和数据分割的时候可以减少很多的时间。

  • 需要注意:stringstream所申请的对象需要每次使用完之后,需要进行清空,调用clear(),函数即可,因为缓冲区内的数据还在缓冲区。如图所示:
    在这里插入图片描述
    可以看到,ss中的数据并没有因为输出到其他字符串中而消失,所以,一定要调用clear()进行清空。
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/736014
推荐阅读
  

闽ICP备14008679号