C++中各种基本数据类型转换为string类型

来源:互联网 发布:js中使用java变量 编辑:程序博客网 时间:2024/05/21 19:40

string 转 long 

那必须是万年atoi(),不过得配合c_str()使用!


[plain] view plain copy
  1. #include <string>  
  2. #include <iostream>  
  3. #include <stdlib.h>  
  4. using namespace std;  
  5. int main ()  
  6. {  
  7.     string a = "1234567890";  
  8.     long b = atoi(a.c_str());  
  9.     cout<<b<<endl;  
  10.     return 0;  
  11. }  


注意:atoi()在 stdlib.h


但是,这不是今天的重点!!!更加变态的方法,用String stream

[cpp] view plain copy
  1. long stol(string str)  
  2. {  
  3.     long result;  
  4.     istringstream is(str);  
  5.     is >> result;  
  6.     return result;  
  7. }  


long 转 string 


[cpp] view plain copy
  1. string ltos(long l)  
  2. {  
  3.     ostringstream os;  
  4.     os<<l;  
  5.     string result;  
  6.     istringstream is(os.str());  
  7.     is>>result;  
  8.     return result;  
  9.   
  10. }  




太变态的string流


测试测试所有的基础类型转换


string 转 int

[cpp] view plain copy
  1. int stoi(string str)  
  2. {  
  3.     int result;  
  4.     istringstream is(str);  
  5.     is >> result;  
  6.     return result;  
  7. }  

通过!

string 转float 

[cpp] view plain copy
  1. float stof(string str)  
  2. {  
  3.     float result;  
  4.     istringstream is(str);  
  5.     is >> result;  
  6.     return result;  
  7. }  

通过!

string 转double

[plain] view plain copy
  1. double stod(string str)  
  2. {  
  3.     double result;  
  4.     istringstream is(str);  
  5.     is >> result;  
  6.     return result;  
  7. }  

通过!


int 转 string

[cpp] view plain copy
  1. string itos(int i)  
  2. {  
  3.     ostringstream os;  
  4.     os<<i;  
  5.     string result;  
  6.     istringstream is(os.str());  
  7.     is>>result;  
  8.     return result;  
  9.   
  10. }  

通过!

float 转 string

[cpp] view plain copy
  1. string ftos(float f)  
  2. {  
  3.     ostringstream os;  
  4.     os<<f;  
  5.     string result;  
  6.     istringstream is(os.str());  
  7.     is>>result;  
  8.     return result;  
  9.   
  10. }  

通过!

double 转 string

[cpp] view plain copy
  1. string dtos(double d)  
  2. {  
  3.     ostringstream os;  
  4.     os<<d;  
  5.     string result;  
  6.     istringstream is(os.str());  
  7.     is>>result;  
  8.     return result;  
  9.   
  10. }  

通过!


* 转string

[cpp] view plain copy
  1. string *tos(* i)     //改一下函数名,改一下类型,搞定  
  2. {  
  3.     ostringstream os;  
  4.     os<<i;  
  5.     string result;  
  6.     istringstream is(os.str());  
  7.     is>>result;  
  8.     return result;  
  9.   
  10. }  

将*换成想要的类型就可以执行 *转string


string 转 *

[cpp] view plain copy
  1. * sto*(string str) //改一下函数名,变量类型,搞定  
  2. {  
  3.     * result;  
  4.     istringstream is(str);  
  5.     is >> result;  
  6.     return result;  
  7. }  
将*换成想要的类型就可以执行 string转*

也可以重载函数,达到万能函数转换




这些测试完全是自己不想写项目,偷懒写点文章安慰自己!囧~


记得包含头文件#include <sstream>


总结:使用string 流和标准io流其实本身就是流,一个原理的,不同调用方法

0 0
原创粉丝点击