分享

c++string与数字之间的转换

 herowuking 2015-09-05

一、转 数字

 1: //-------------------------------------

 2: //功能:C++ string 转 int 
 3: //环境:VS2005 
 4: //------------------------------------- 
 5: 
 6: #include "stdafx.h" 
 7: #include <iostream> 
 8: #include <sstream> 
 9: 
 10: using namespace std; 
 11: 
 12: template <class Type> 
 13: Type stringToNum(const string& str) 
 14: { 
 15: istringstream iss(str); 
 16: Type num; 
 17: iss >> num; 
 18: return num; 
 19: } 
 20: 
 21: int main(int argc, char* argv[]) 
 22: { 
 23: string str("00801"); 
 24: cout << stringToNum<int>(str) << endl; 
 25: 
 26: system("pause"); 
 27: return 0; 
 28: } 

二、转 string

itoa(   int   value,   char   *string,   int   radix   );  
    第一个参数:你要转化的int;  
    第二个参数:转化后的char*;  
    第三个参数:你要转化的进制;  

//------------------------------------- 
//功能:C++ int 转 string (使用atoi)  
//环境:VS2005 
//------------------------------------- 

#include "stdafx.h" 
#include <iostream> 
using namespace std; 

int main(int argc, char* argv[]) 
{ 
 int n = 30; 
 char c[10]; 
 
 itoa(n, c, 2); 
 cout << "2-> " << c << endl; 

 itoa(n, c, 10); 
 cout << "16-> " << c << endl; 

 itoa(n, c, 16); 
 cout << "10-> " << c << endl; 

 system("pause"); 
 return 0; 
}

 

参考http://pppboy.blog.163.com/blog/static/302037962010378296766/

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多