C++ 中 string 和其它类型的相互转化。

sscanf、sprintf 也可以用,但是不建议使用,实际上 c++ 实现 string 和其他数据类型的转换很容易完成,见如下代码:

[cpp]  view plain copy
  1. #include <iostream>  
  2. using std::cout;  
  3. using std::endl;  
  4. #include <string>  
  5. using std::string;  
  6.   
  7. #include <sstream>  
  8. using std::stringstream;  
  9. using std::ostringstream;  
  10.   
  11. template <class T>    
  12. string toString(const T& s);   
  13.   
  14. int main()   
  15. {  
  16.     string value = "";   
  17.     int inum = 0;  
  18.     double dnum = 0.0;  
  19.     value = "123";  
  20.     stringstream strStream;  
  21.     strStream << value;   
  22.     strStream >> inum;  
  23.     strStream.clear();  // 必须 clear,否则下一次调用不成功  
  24.   
  25.     value = "123.45";  
  26.     strStream << value;  
  27.     strStream >> dnum;  
  28.   
  29.     cout << inum << " " << dnum <<endl;  
  30.       
  31.     string test = "";   
  32.     test = toString(dnum);  
  33.     cout << test << endl;  
  34.   
  35.     return 0;  
  36. }  
  37.   
  38. //其它类型转化为string类型  
  39. template <class T>    
  40. string toString(const T& s) {  
  41.     ostringstream os;  
  42.     os << s;  
  43.     return os.str();  
  44. }  


注意:若文本中数据是科学计数型,例如文本是:1.44e-07   仍能正常转化.


参考:

istringstream, ostringstream, stringstream 实现数据类型转化为 string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值