整数与字符串的互相转化

//整数转化成字符串,只要在数字后面加‘0’再逆序即可。整数加‘0’就会隐性转化成char类型的数
//实现itoa函数的功能
#include "stdafx.h" #include <iostream> #include<stdio.h> int main() { int num=12345,i=0,j=0; char temp[7],str[7]; while(num){ temp[i]=num%10+'0'; i++; num=num/10; } temp[i]=0; printf(" temp=%s ",temp); i=i-1; printf(" temp=%d ",i); while(i>=0){ str[j]=temp[i]; j++; i--; } str[j]=0; printf(" string=%s ",str); system("pause"); return 0; }


字符串转化成整数,可以采用先减‘0’再乘10累加的办法,字符串减‘0’就会隐性转化成int类型的数

#include "stdafx.h"
#include <iostream>
#include<stdio.h>
int main()
{
 int num=12345,i=0,j=0,sum=0;
 char temp[7]={'1','2','3','4','5',''},str[7];
 while(temp[i]){
  sum=sum*10+(temp[i]-'0');
  i++;
 }
 printf(" sum=%d
",sum);
 system("pause");
 return 0;
}
原文地址:https://www.cnblogs.com/mj-selina/p/5808530.html