整数转换为字符串,可以采用将每位数字后面加‘0’,再逆序的方法,整数加‘0’会隐形的转化为char类型的数。
#include "stdafx.h" #include<iostream> #include<string> using namespace std;
int _tmain(int argc, _TCHAR* argv[]) { char c; int a=1; c=a+'0'; cout<<c<<endl; int num=12345; char *cnum = new char[5]; int i=0; while(num){ int decate = num%10; cnum[i++]=decate+'0'; num=num/10; } int len = sizeof(cnum)/sizeof(char); cout<<len<<endl; for(int i=0;i<len/2;i++){ int temp=cnum[i]; cnum[i]=cnum[len-i]; cnum[len-i]=temp; } cout<<cnum<<endl; return 0; }
|
反过来,数字字符串转换为数字,为每个字符减‘0’,就可以了
int _tmain(int argc, _TCHAR* argv[]) { char str[7]={'1','2','3','4','5','6','\0'}; int sum = 0; int i = 0; while(str[i]){ sum = sum*10+(str[i]-'0'); i++; } cout<<sum<<endl; return 0; }
|
阅读(689) | 评论(0) | 转发(0) |