码迷,mamicode.com
首页 > 其他好文 > 详细

整数与字符串的互相转化

时间:2016-08-25 23:54:01      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:

//整数转化成字符串,只要在数字后面加‘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\n",temp); i=i-1; printf(" temp=%d\n",i); while(i>=0){ str[j]=temp[i]; j++; i--; } str[j]=0; printf(" string=%s\n",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,\0},str[7];
 while(temp[i]){
  sum=sum*10+(temp[i]-0);
  i++;
 }
 printf(" sum=%d\n",sum);
 system("pause");
 return 0;
}

 

整数与字符串的互相转化

标签:

原文地址:http://www.cnblogs.com/mj-selina/p/5808530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!