字符串转整数类型
#include <stdio.h>
#include <ctype.h>
int my_atoi(char* pstr)
{
int Ret_Integer = 0;
int Integer_sign = 1;
if(pstr == NULL) {
printf("Pointer is NULL\n");
return 0;
}
while(isspace(*pstr)){
pstr++;
}
if(*pstr == '-') {
Integer_sign = -1;
}
if(*pstr == '-' || *pstr == '+') {
pstr++;
}
while(*pstr >= '0' && *pstr <= '9'){
Ret_Integer = Ret_Integer * 10 + *pstr - '0';
pstr++;
}
Ret_Integer = Integer_sign * Ret_Integer;
return Ret_Integer;
}
int main()
{
int c = 0;
c = my_atoi("12") + my_atoi("11");
printf("c = %d\n",c);
printf("atoi("132")=%d\n",my_atoi("132"));
printf("atoi("-987")=%d\n",my_atoi("-987"));
return 0;
}
整数类型转字符串
#include <limits.h>
#include <stdio.h>
#include <string.h>
#define N 48
char s[N];
void reverse(char s[]){
int i, j, n=strlen(s), tmp;
for (i=0, j=n-1; i<j; i++, j--)
tmp = s[i], s[i] = s[j], s[j] = tmp;
}
void itoa(int n, int base)
{
int i=0, sign;
char c;
if ((sign=n) < 0)
n = -n;
do {
switch((c=n%base)){
case 0: case 1: case 2: case 3: case 4:
case 5: case 6: case 7: case 8: case 9:
s[i++] = c + '0'; break;
case 10: case 11: case 12:
case 13: case 14: case 15:
s[i++] = c + 'a' - 10; break;
}
}while ((n/=base) > 0);
if (sign < 0) s[i++] = '-';
s[i] = '\0';
reverse(s);
printf("%s\n", s);
}
int main(){
itoa(INT_MIN, 3);
itoa(123, 16);
itoa(123, 10);
itoa(123, 8);
return 0;
}
#include <stdio.h>
#include <string.h>
#define N 48
char s[N];
void reverse(char s[]){
int i, j, n=strlen(s), tmp;
for (i=0, j=n-1; i<j; i++, j--)
tmp = s[i], s[i] = s[j], s[j] = tmp;
}
char *myitoa(int n){
int i=0, sign = n;
char c;
if (sign < 0)
n = -n;
do {
s[i++] = n%10 + '0';
n = n/10;
} while (n> 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
return s;
}
int main(){
printf("%s\n", myitoa(123456789));
return 0;
}