字符串转化为整形的各类情况:
char *str1 = "12345"; //普通
char *str2 = "+12345"; //正数
char *str3 = "-12345"; //负数
char *str4 = " 12345"; //前面有若干个空格
char *str5 = " 1 2 3 4 5"; //数字间存在空格
char *str6 = "0x12345"; //十六进制
char *str7 = "012345"; //八进制
char *str8 = "abc123"; //含其他字符
char *str8 = "abc123"; //含其他字符
代码如下:
#include<stdio.h> int my_atoi(const char *str) { int result = 0; //存放转换后的值 int sign = 1; //符号位 int weight = 10; //权值(十进制,八进制,十六进制) while(*str != '\0') { if(*str == '+') //表明是正数 { sign = 1; str++; //将'+'掠过 } if(*str == '-') //表明是负数 { sign = -1; str++; //将'-'掠过 } /*if(*str == '0' && *(++str) != 'x') { weight = 8; //注意!!!!!:此处不能加str++,否则会错失一个字符 // str++; 因为执行完*(++str) != 'x'后,str已经指向一个未完全判断的字符(虽然不等于x) } if(*str == '0' && *(++str) == 'x')//表明是16进制 { weight = 16; str++; //将'x'掠过 }*/ if(*str == '0') { if(*(str + 1) == 'x') { weight = 16; str += 2; //将'0'和'x'掠过 } else { weight = 8; str += 1; //将'0'掠过 } } if(*str >= '0' && *str <= '9') { result = result * weight + (*str - '0'); str++; } else { str++;//非有效字符全部掠过(+ - 0x x exp) } } return result * sign; } int main() { char *str1 = "12345"; //普通 char *str2 = "+12345"; //正数 char *str3 = "-12345"; //负数 char *str4 = " 12345"; //前面有若干个空格 char *str5 = " 1 2 3 4 5";//数字间存在空格 char *str6 = "0x12345"; //十六进制 char *str7 = "012345"; //八进制 char *str8 = "abc123"; printf("%6d\n",my_atoi(str1)); printf("%6d\n",my_atoi(str2)); printf("%6d\n",my_atoi(str3)); printf("%6d\n",my_atoi(str4)); printf("%6d\n",my_atoi(str5)); printf("%6d\n",my_atoi(str6)); printf("%6d\n",my_atoi(str7)); printf("%6d\n",my_atoi(str8)); return 0; }
原文地址:http://blog.csdn.net/zongyinhu/article/details/45049533