字符与数字的转换
核心思想: 整数转化为字符串:加 ‘0’ ,然后逆序。 字符串转化整数:减 ‘0’,乘以10累加。 注:整数加 ‘0’后会隐性的转化为char类型;字符减 ‘0’隐性转化为int类型
如果用函数实现 C++11 直接to_string(int i)将整形转为string类型字符串
下面的函数转为字符串是char类型 最好用:stringstream
int n = 123456; char p[100] = {}; stringstream s; s << n; s >> p;
其次:springf、sscanf // 数字转字符串 sprintf(str, “%d”, num); // 字符串转数字 sscanf(str, “%d”, &rsl); 再其次:itoa、atoi 1、数字转字符 itoa()函数有3个参数:数字、写入转换结果的目标字符串、进制 itoa(num, string, 10); // 按10进制转换 2、字符转数字 char str[4] = {‘1’, ‘2’, ‘3’, ‘4’}; int num = atoi(str);
面试自己手写实现:
1.整数转字符串
#include <iostream>
using namespace std;
int main() {
// 整数转字符串
int num = 1234;
char temp[7], str[7];
int i = 0, j = 0;
while(num) {
// 整数转字符串: +'0'
temp[i++] = num % 10 + '0';
num = num / 10;
}
// 刚刚转化的字符串是逆序的
while(i >= 0) {
str[j++] = temp[--i];
}
cout << str << endl;
return 0;
}
2.字符串转整数
#include <iostream>
using namespace std;
int main() {
char str[5] = {'1', '2', '3', '4', '\0'};
int num = 0;
int i = 0;
while(str[i]) {
num = num * 10 + (str[i++] - '0');
}
cout << num << endl;
return 0;
}
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。