首先就是运用<string>头文件中的 stoi 函数(可以根据 string to int 缩写为 s to i这样去记忆),函数原型inline int stoi(const string& _Str, size_t* _Idx = nullptr, int _Base = 10)。第一个参数是要转化的字符串(里面是int型数据),要注意该字符串长度不能超过10.第二和第三个参数不用管。
#include<string>
#include<iostream>
using namespace std;
int main() {
string s = "123";
cout << stoi(s) << endl; //输出为 123。
cout << stoi("123") << endl; //输出为 123。
// s = "abc"; stoi(s); //这样是错的,不能有字母。
return 0;
}同理,还有 stod(将字符串转化为double型)、itos(将整形转化为字符串)等等。
第二种就麻烦一点,因为不能直接对string强转为int。将string中的第i个字符减去'0'(或者48)后强转为int型(直接对char*强转为int型的话得到的数不是字符里的数据),再乘以10的(n - 1 - i)次方,累加。
#include<string>
#include<iostream>
using namespace std;
int main() {
string s = "123";
cout << int(s[0]) << endl; //得到的数是49而不是1。
int t = 0;
int n = s.length(); //求出s的长度,为3.
for (int i = 0; i < n; i++) {
t += int(s[i] - '0') * pow(10, (n - 1 - i));
}
cout << t << endl; //输出 123。
return 0;
}顺便提一下,将整形转化为字符串型可以使用to_string函数。
#include<string>
using namespace std;
int main(){
int a = 4;
string result = to_string(a);
//将整数4转化为字符串型result
return 0;
}版权声明:本文为m0_60492395原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。