一:c++11库函数()
前提:编译器能够支持c++11标准(dev-c++需要设置)
1、字符串转成数值(stoi、stol、stof、stod)
#include<iostream>
#include<string>//函数都包含在<string>文件中
using namespace std;
int main()
{
string str="123.123";
int t;
long l;
float f;
double d;
t=stoi(str,0,10);//第一个形参:字符串变量,第二个:字符串的起始位置,第三个:想要转换的进制
l=stol(str,0,10);
f=stof(str);//对于浮点数,直接传递字符串变量即可
d=stod(str);
cout<<t<<endl;
cout<<l<<endl;
cout<<f<<endl;
cout<<d<<endl;
return 0;
}
输出:
2、数字转成字符串( to_string() )
同样是<string>中的函数:to_string(),将数值形参传递将返回一个字符串
#include<iostream>
#include<string>
using namespace std;
int main()
{
double d=123.123;
string str;
str=to_string(d);
cout<<str;
return 0;
}
输出:123.123000
对于浮点数类型,字符串还会包含几个"000"
二:在c++11标准之前,还有一个函数也是常用来进行类型转换:<sstream>库的stringstram类
这个类可以实现各种类型的转换
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
double d;
string str="123.123";
stringstream ss;
ss<<str;
ss>>d;
cout<<d<<endl;
return 0;
}
输出:123.123
注意:在对同一个stringstream对象重复赋值,就需要先对流使用clear()函数清空流的状态,此时流占用的内存没有改变,会一直增加(stringstream不主动释放内存),若想改变内存(一般是清除内存,减少内存消耗),需要再配合使用str("")清空stringstream的缓存。
例:
#include <iostream>
#include <string>
#include <sstream>//stringstream类的库
using namespace std;
int main()
{
int a=10;
double b=1.11;
stringstream ss;
string str1,str2;
ss<<a;
ss>>str1;
ss.clear();//清空流的状态,以便重新赋值
ss<<b;//重新赋值
ss>>str2;
cout<<str1<<endl;
cout<<str2<<endl;
return 0;
}
输出:
10
1.11
--------------------------------
Process exited after 0.04233 seconds with return value 0
请按任意键继续. . .
对于浮点数转换,使用stringstream类,字符串后面就不会含有"000"了