std::string与int、double相互转换

      std::string为library type,而int、double为built-in type,两者无法互转。

      方法一,使用function template的方式将int转std::string,将double转std:string。

ExpandedBlockStart.gif 代码
#include  < iostream >
#include 
< sstream >
#include 
< string >

using   namespace  std;

template 
< class  T >  
void  convertFromString(T  & const  std:: string   & );

template 
< class  T >  
string  ConvertToString(T);

int  main() {
  
string  s( " 123 " );
  
string  s1;

  
//  Convert std::string to int、double
   int  i  =   0 ;
  convertFromString(i,s);
  cout 
<<  i  <<  endl;

  
double  d  =   0 ;
  convertFromString(d,s); 
  cout 
<<  d  <<  endl;

  
//  Convert int、double to std::string
   int  i1  =   123 ;
  s1 
=  ConvertToString(i1);
  cout 
<<  s1  <<  endl;

  
double  d1  =   123.123
  s1 
=  ConvertToString(d1);
  cout 
<<  s1  <<  endl;

  
// stringstream除了基本类型的转换,也支持char *的转换
  stringstream stream; 
  
char  result[ 8 ] ; 
  
int  i2  =   8888 ;
  stream 
<<  i2;                                             // 向stream中插入8888 
  stream  >>  result;                                         // 抽取stream中的值到result 
  cout  <<  result  <<  endl;                                 //  屏幕显示 "8888" 
    
  
// 再进行多次转换的时候,必须调用stringstream的成员函数clear()
   int  second;
  stream.clear();                                        
// 在进行多次转换前,必须清除stream 
  stream  <<   true ;                                         // 插入bool值 
  stream  >>  second;                                         // 提取出int 
  cout  <<  second  <<  endl; 

  
return   0 ;
}

template 
< class  T >
void  convertFromString(T  & value,  const   string   & s) {
  stringstream ss(s);
  ss 
>>  value;
}

template 
< class  T >  
string  ConvertToString(T value) {
  stringstream ss;
  ss 
<<  value;
  
return  ss.str();
}

 
        方法二,先利用c_str()轉成C string,再用atoi()與atof()。

ExpandedBlockStart.gif 代码
#include  < iostream >
#include 
< string >
#include 
< cstdlib >

using   namespace  std;
 
int  main() {
  
string  s  =   " 123 " ;
  
double  n  =  atof(s.c_str());
  
// int n = atoi(s.c_str());
   
  cout 
<<  n  <<  endl;
}

 

 

转载于:https://www.cnblogs.com/zqrferrari/archive/2010/05/18/1738408.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值