#include<iostream>
#include<string.h>
#include<string>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int stoi(char *s){
int len = strlen(s);
int t =0;
int k = 0;
int sum = 0;
for(int i = 0;i<len;i++){
k = i;
t = s[i]-'0'; //从第0位开始取 第一次 t = 1 (第二次 t = 2)
while(k<len-1){
t*=10; // 第一次 t = 1000 (第二次 t = 200)
k++;
}
sum+=t; //sum+=t = 1000; (第二次 sum = 1200)
}
return sum;
}
char* itos(int a){
char s[20]="";
int len =0;
int s_len = 0;
int t = 0;
int k = 1;
int temp = a;
while(temp>0){
temp=temp/10;
len++; //计算a的长度
}
while(a>0){
while(t<len-1){ //以1234为例:
k*=10; //第一次算的 k = 1000; (第二次算的 k = 100)
t++;
}
s[s_len++]='0'+(a/k); //a/k = 1234/1000 = 1 取得第一位为1,赋给s的第0个位置
a-=k*(a/k); //a-=k*(a/k) = 1234 - (1000*1) = 234
t=0;k=1; //重置 t,k
len--; //完成一位计算,则长度-1
}
cout<<s<<endl;
return s;
}
int main(){
//字符串转换为整数
char s[] = "1234";
cout<<stoi(s)<<endl;
//整数转换为字符串
int a = 1234;
cout<<itos(a)<<endl;
return 0;
}
运行结果:
1234 //整型
1234 //字符串