一.to_string函数:
to_string函数可以将数字常量转化为字符串
头文件:#include < cstring> 或 #include <>
例:
stirng str = to_string(int x); //参数为int型数字常量
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int x = 566;
string str = to_string(x);
cout << str << endl;
cout << str[0] << endl;
return 0;
}
输出样例:
566
5
注: 参数的类型可以是int,long, double ,long long。
二.stoi函数:
将 n 进制的字符串转化为十进制
stoi(字符串,起始位置,n进制(默认10进制)),将 n 进制的字符串转化为十进制
头文件:#include < cstring>
例:
int x = stoi(string str)
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str = "100";
int x = stoi(str, 0, 2); //将二进制"100"转化为十进制x
cout << x << endl;
return 0;
}
输出样例:
4
注: stoi()函数如果传入的字符串s中含有不是数字的字符,则只会识别到从开头到第一个非法字符之 前,如果第一个字符就是非法字符则会报错