stringstream常见用法

目录

构造函数 

输出字符串 

修改和清空字符串 

 利用 stringstream 去除字符串空格

 利用stringstream去除指定的字符

stringstream 数据库 <sstream>

构造函数 

  1. 创建一个对象,向对象输入字符串:
string x="abcdefg";
	stringstream ss;
	ss<<x;

2.字符串初始化(一般用这个方便很多) 


	string x="abcdefg";
	stringstream ss(x);

输出字符串 

 调用str()函数 str()函数可以将其他类型的数据转换为字符串类型,从而方便我们输出和处理数据

cout<<ss.str()<<endl;

修改和清空字符串 

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
	string x="abcdefgh";
	//初始化
	stringstream ss(x);
	cout<<ss.str()<<endl;
	//修改字符串
	ss.str("1234565");
	cout<<ss.str()<<endl;
	//清空字符串
	ss.str(" ");
	cout<<ss.str()<<endl;
	cout<<"0"<<endl;
	return 0;
}

 

 利用 stringstream 去除字符串空格

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
    string x="a b c d efg h j";
    stringstream ss(x);
    string s;
    while(ss>>s)
    {
    	cout<<s<<endl;
	}
	return 0;
}

 

 利用stringstream去除指定的字符

 借用getline()函数

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
    string x="a, b, c,d,efg,h,j";
    stringstream ss(x);
    string s;
    while(getline(ss,s,','))
    {
    	cout<<s<<endl;
	}
	return 0;
}

 

 字符串转化成其他类型 int double float

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
    string x="12345678";
    stringstream ss(x);
    int p;
    ss>>p;//就想象成读入给p p就有值了
    cout<<p<<endl;
    cout<<p/2<<endl;
	return 0;
}

 

 文章来源地址https://uudwc.com/A/mJ8oJ

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
    string x="12 34 56 78";
    stringstream ss(x);
    int p;
    while(ss>>p)
    {
    	cout<<p<<endl;
    	cout<<"*** "<<p/2<<endl;
	}
	return 0;
}

 

 

 

原文地址:https://blog.csdn.net/m0_74015873/article/details/132248703

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

上一篇 2023年08月12日 22:39
[静态时序分析简明教程(九)]多周期路径set_multicycle_path
下一篇 2023年08月12日 22:40