转:C++ string的万能转换,从long string 之间的转换来看看
(2016-09-08 20:21:29)
string 转 long
那必须是万年atoi(),不过得配合c_str()使用!
[plain] view plain copy
-
#include
-
#include
-
#include
-
using
namespace std; -
int
main () -
{
-
string a = "1234567890"; -
long b = atoi(a.c_str()); -
cout<<b<<endl; -
return 0; -
}
注意:atoi()在 stdlib.h
但是,这不是今天的重点!!!更加变态的方法,用String stream
[cpp] view plain copy
-
long
stol(string str) -
{
-
long result; -
istringstream is(str); -
is >> result; -
return result; -
}
long 转
string
[cpp] view plain copy
-
string
ltos( longl) -
{
-
ostringstream os; -
os<<l; -
string result; -
istringstream is(os.str()); -
is>>result; -
return result; -
-
}
太变态的string流
测试测试所有的基础类型转换
string 转 int
[cpp] view plain copy
-
int
stoi(string str) -
{
-
int result; -
istringstream is(str); -
is >> result; -
return result; -
}
通过!
string
转float
[cpp] view plain copy
-
float
stof(string str) -
{
-
float result; -
istringstream is(str); -
is >> result; -
return result; -
}
通过!
string 转double
[plain] view plain copy
-
double
stod(string str) -
{
-
double result; -
istringstream is(str); -
is >> result; -
return result; -
}
通过!
int 转 string
[cpp] view plain copy
-
string
itos( inti) -
{
-
ostringstream os; -
os<<i; -
string result; -
istringstream is(os.str()); -
is>>result; -
return result; -
-
}
通过!
float 转 string
[cpp] view plain copy
-
string
ftos( floatf) -
{
-
ostringstream os; -
os<<f; -
string result; -
istringstream is(os.str()); -
is>>result; -
return result; -
-
}
通过!
double 转 string
[cpp] view plain copy
-
string
dtos( doubled) -
{
-
ostringstream os; -
os<<d; -
string result; -
istringstream is(os.str()); -
is>>result; -
return result; -
-
}
通过!
* 转string
[cpp] view plain copy
-
string
*tos(* //改一下函数名,改一下类型,搞定i) -
{
-
ostringstream os; -
os<<i; -
string result; -
istringstream is(os.str()); -
is>>result; -
return result; -
-
}
将*换成想要的类型就可以执行 *转string
string 转 *
[cpp] view plain copy
-
*
sto*(string //改一下函数名,变量类型,搞定str) -
{
-
* result; -
istringstream is(str); -
is >> result; -
return result; -
}
也可以重载函数,达到万能函数转换
记得包含头文件#include
总结:使用string 流和标准io流其实本身就是流,一个原理的,不同调用方法。
前一篇:转:基于 Token 的身份验证
后一篇:转: C++时间与字符串转换