使用stringstream对象简化类型转换

< sstream>库定义了三种类:istringstream、ostringstream和stringstream,分别用来进行流的输入、输出和输入输出操作。另外,每个类都有一个对应的宽字符集版本。简单起见,我主要以stringstream为中心,因为每个转换都要涉及到输入和输出操作。

对象声明方式
stringstream ss;

使用方法

stringstream ss;
int n=0;
char s[]="123456";
ss<<s;
ss>>n;  //n=123456,n发生改变

重复使用stringstream对象
stringstream对象的构造和析构函数通常是非常耗费CPU时间的,重复使用stringstream对象可以提高程序的效率。但是重复利用前需要调用clear()函数,否则会出错。

stringstream对象的特点功能
在我看来stringstream对象的强大之处在于它对于字符串的分割,在一个字符串中包含空格的时候,使用stringstream可以很方便的分割成为多个字符串。
举例

char s[100]="jdfhufgh fjhg lkj dd";
char temp[100];
stringstream ss(s);
while(ss>>temp)
cout<<temp<<' ';

输出:jdfhufgh fjhg lkj dd

从以上代码可以看出,原字符串s被截断成4个字符串,是很方便的。当然有人会问了有了截断,必然会有字符串连接。当然,字符串连接的话请使用string类对象。
其实sprintf()也能实现字符类型转换,但是sprintf使用起来容易出错,这里就不加赘述了。

对sprintf想了解更多请点击sprintf详解

stringstream测试代码

#include<iostream>
#include<sstream>
using namespace std;
int main()
{
    stringstream st;
    char s[40]="123646 35456 6546";
    char s1[40];
    int x;
    st<<s;
    while(st>>x)
    {
    cout<<x<<endl;
    }

    //对象重用
    st.clear(); 
    string str1="jfhgf6454 646 6465 fgkjfhi";
    string str2="";
    st<<str1;
    while(st>>str2)
    {
        cout<<str2<<endl;
    }
    return 0;
}

如有不当之处欢迎指出!!

转载于:https://www.cnblogs.com/flyawayl/p/8305612.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值