由于最近在刷题时碰到许多这样的问题,写个博客自己整理下
- 字符串型数字转纯数字
例:“1234”->1234
- atoi+c_str()
代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s="1234";
int a= atoi(s.c_str());
cout<<a<<endl;
}
输出:1234
- stoi函数
代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
string s="1234";
int a= stoi(s);
cout<<a<<endl;
}
输出:1234
区别:
一、atoi()的参数是 const char* ,因此对于一个字符串str我们必须调用
c_str()的方法把这个string转换成 const char*类型的,而stoi()的参数
是const string*,不需要转化为 const char*;
二、stoi()会做范围检查,默认范围是在int的范围内的,如果超出范围的
话则会runtime error!而atoi()不会做范围检查,如果超出范围的话,
超出上界,则输出上界,超出下界,则输出下界;
- 字符型数字转纯数字
例:‘9’->9
- ASCII码转换
代码:
#include <iostream>
#include <string>
using namespace std;
int main(){
char s='9';
int a=s-'0';
cout<<a<<endl;
}
输出:9
- 数字转字符串(可以是double类型)
- sstrem输入输出流
代码:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
double x=3.14159;
string str;
stringstream ss;
//将double类型的值放入输入流中
ss << x;
//从sstream中抽取前面插入的int类型的值,赋给string类型
ss >> str;
cout <<str<<endl;
if (typeid(str) == typeid(string))
cout<<"str已转为字符串"<<endl;
return 0;
}
输出:
3.14159
str已转为字符串
- to_string方法,浮点数会附带小数点后六位,不足补零
代码:
#include <iostream>
#include<string>
using namespace std;
int main()
{
double x=3.14159;
string str;
str = to_string(x);
cout << str;
return 0;
}
输出:3.141590