您的位置:首页 > 编程语言 > C语言/C++

C++字符串和整数相互转换

2017-08-04 22:25 405 查看
//将整数转化为字符串,并且不使用itoa函数
#include<stdio.h>
void main()
{
int n = 12345;
char temp[6] = {0};
int i = 0;
while (n)
{
temp[i++] = n % 10 + '0';//整数加上‘0’隐性转化为char类型数
n /= 10;
}
char dst[6] = {0};
for (int j = 0; j < i; j++)
{
dst[j] = temp[i-1-j];
}
printf("%s\n", dst);
}

//将字符串转化为整数
#include<stdio.h>
void main()
{
char temp[6] = {'1','2','3','4','5'};
int n = 0, i = 0;
while (temp[i])
{
n = n * 10 + (temp[i++] - '0');//隐性转化为整数
}
printf("%d\n", n);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: