stringstream转换

在这之前,在杭电刷题的时候,并没有注意到这个好东西。

使用stringstream对象简化类型转换
C++标准库中的<sstream>提供了比ANSI C的<stdio.h>更高级的一些功能,即单纯性、类型安全和可扩展性。在本文中,我将展示怎样使用这些库来实现安全和自动的类型转换。

为什么要学习

如果你已习惯了<stdio.h>风格的转换,也许你首先会问:为什么要花额外的精力来学习基于<sstream>的类型转换呢?也许对下面一个简单的例子的回顾能够说服你。假设你想用sprintf()函数将一个变量从int类型转换到字符串类型。为了正确地完成这个任务,你必须确保证目标缓冲区有足够大空间以容纳转换完的字符串。此外,还必须使用正确的格式化符。如果使用了不正确的格式化符,会导致非预知的后果。下面是一个例子:

int n=10000;

chars[10];

sprintf(s,”%d”,n);// s中的内容为“10000”

到目前为止看起来还不错。但是,对上面代码的一个微小的改变就会使程序崩溃:

int n=10000;

char s[10];

sprintf(s,”%f”,n);// 看!错误的格式化符

在这种情况下,程序员错误地使用了%f格式化符来替代了%d。因此,s在调用完sprintf()后包含了一个不确定的字符串。要是能自动推导出正确的类型,那不是更好吗?

进入stringstream

由于ns的类型在编译期就确定了,所以编译器拥有足够的信息来判断需要哪些转换。<sstream>库中声明的标准类就利用了这一点,自动选择所必需的转换。而且,转换结果保存在stringstream对象的内部缓冲中。你不必担心缓冲区溢出,因为这些对象会根据需要自动分配存储空间。

----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

比如:

string到int的转换

string result=”10000”;
int n=0;
stream<<result;
stream>>n;//n等于10000

 

stringstream通常是用来做数据转换的。

相比c库的转换,它更加安全,自动和直接。

 

例子一:基本数据类型转换例子 int转string

 

# include <string>
# include <sstream>
# include <iostream> 

int main()
{
    std :: stringstream stream;
    std :: string  result;
    int i  =   1000 ;
    stream  <<  i;  // 将int输入流
    stream  >>  result;  // 从stream中抽取前面插入的int值
    std :: cout  <<  result  <<  std :: endl;  //  print the string "1000"
 

例子二:除了基本类型的转换,也支持char *的转换。

 

# include <sstream>
# include <iostream> 

int main()
{
    std :: stringstream stream;
    char result[ 8 ] ;
    stream  <<   8888 ;  // 向stream中插入8888
    stream  >>  result;  // 抽取stream中的值到result
    std :: cout  <<  result  <<  std :: endl;  //  屏幕显示 "8888"
 

例子三:再进行多次转换的时候,必须调用stringstream的成员函数clear().

 

# include <sstream>
# include <iostream>
int main()
{
    std :: stringstream stream;
    int first ,  second;
    stream <<   " 456 " ;  // 插入字符串
    stream  >>  first;  // 转换成int
    std :: cout  <<  first  <<  std :: endl;
    stream . clear();  // 在进行多次转换前,必须清除stream
    stream  <<   true ;  // 插入bool值
    stream  >>  second;  // 提取出int
    std :: cout  <<  second  <<  std :: endl;
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
大概主要的用法就是这么多,欢迎补充!
例题https://vijos.org/p/1389

转载于:https://www.cnblogs.com/ouyang_wsgwz/p/6486207.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值