1.字符串→整型
int atoi(char s[]) { int i,n,sign; for(i=0;isspace(s[i]);i++)//skip front spaces ; sign=(s[i]=='-')? -1:1; if(s[i]=='+'||s[i]=='-') //skip the sign i++; for(n=0;isdigit(s[i]);i++) n=n*10+(s[i]-'0'); return sign*n; }
2.整型→字符串
void itoa(int n,char s[]) { int i,sign; if((sign=n)<0) n=-n; i=0; do{ s[i++]=n%10+'0'; }while((n/=10)>0); if(sign<0) s[i++]='-'; s[i]='\0'; reverse(s); } void reverse(char s[]) { int c,i,j; for(i=0,j=strlen(s)-1;i<j;i++,j--){ c=s[i]; s[i]=s[j]; s[j]=c; } }
3.字符串→浮点
//atof:translate string into double float double atof(char s[]) { double val,power; int i,sign; for(i=0;isspace(s[i]);i++)//skip space ; sign=(s[i]=='-')?-1:1; if(s[i]=='+'||s[i]=='-') i++; for(val=0.0;isdigit(s[i]);i++) val=val*10.0+(s[i]-'0'); if(s[i]=='.') i++; for(power=1.0;isdigit(s[i]);i++){ val=10.0*val+(s[i]-'0'); power*=10.0; } return sign*val/power; }