stringstream类

前两天再看实验室程序的时候,发现了其中的一些不明白的地方,其中一个就是stringstream,经过查询是stringstream属于STL里面的,而惭愧的是之前听说过STL,却从来没有主动去了解它,因此下了决心要把stringstream给弄懂。stringstream大致有以下几个作用

1.类型转换

#include<bits/stdc++.h>
using namespace std;
int main()
{
	stringstream ss;
	int n;
	
	ss<<"123456";
	ss>>n;
	cout<<n<<endl;
	
	return 0;
 } 

该程序输出123456

可以通过stringstream来将字符串转换成int类型输出,另外,在多次使用stringstream时,要使用clear函数,例如

#include<bits/stdc++.h>
using namespace std;
int main()
{
	
    stringstream ss;
    int first, second;
    ss<< "456"; //插入字符串
    ss>> first; //转换成int
    cout << first <<endl;
    ss.clear(); //在进行多次转换前,必须清除stream
    ss << true; //插入bool值
    ss >> second; //提取出int
    cout << second << endl;
 } 

该程序输出456和1

2.ss.str()函数可以返回字符串数据

#include<bits/stdc++.h>
using namespace std;
int main()
{
	
stringstream istr;
    istr.str("1 56.7");
    //上述两个过程可以简单写成 istringstream istr("1 56.7");
    cout << istr.str() << endl;
    int a;
    float b;
    istr >> a;
    cout << a << endl;
    istr >> b;
    cout << b << endl;
    return 0;
 } 

输出1和56.7,空格可以分开字符串完成不同变量的赋值。

3.put函数可以给stringstream变量赋值,但是构造的时候对象内已经存在字符串数据的时候,那么增长操作的时候不会从结尾开始增加,而是修改原有数据,超出的部分增长。

#include<bits/stdc++.h>
using namespace std;
int main()
{
	
stringstream ostr;
    ostr.str("abc");
    string fstr = ostr.str();
    cout<<fstr<<endl;
    //如果构造的时候设置了字符串参数,那么增长操作的时候不会从结尾开始增加,而是修改原有数据,超出的部分增长
ostr.put('d');
ostr.put('e');
ostr<<"fg";

    string gstr = ostr.str();
    cout<<gstr;
    system("pause");
 } 
发布了23 篇原创文章 · 获赞 3 · 访问量 4037

猜你喜欢

转载自blog.csdn.net/weixin_43098069/article/details/84837765
今日推荐