1、能夠將從當前開始的字符(數字或+、-)到第一個不是數字的字符結束的數字字符串,轉化成整數;
這個也就是有人在blog中談論的前綴匹配。
2、需要注意的指針在這個過程中的指向發生了改變
下面給出我的atoi實現代碼
int aatoii(const char * str)
{
if(str == NULL) return 0;
int result = 0;
int sign = 1;
if( ('0'<= str[0] && str[0] <= '9') ||(str[0]=='-') || str[0]=='+')
{
if(str[0] == '+' || str[0] == '-')
{
if(str[0]=='-')
{
sign = -1;
}
str++;
}
}
else
{
return 0;
}
while('0'<= *str && *str <= '9')
{
result = result*10 + (*str++ - '0');
}
return result;
}
{
if(str == NULL) return 0;
int result = 0;
int sign = 1;
if( ('0'<= str[0] && str[0] <= '9') ||(str[0]=='-') || str[0]=='+')
{
if(str[0] == '+' || str[0] == '-')
{
if(str[0]=='-')
{
sign = -1;
}
str++;
}
}
else
{
return 0;
}
while('0'<= *str && *str <= '9')
{
result = result*10 + (*str++ - '0');
}
return result;
}
修改版:
int aatoii(const char * str)
{
if(str == NULL) return 0;
int result = 0;
int sign = 1;
if( ('0'<= str[0] && str[0] <= '9') ||(str[0]=='-') || str[0]=='+')
{
if(str[0] == '+' || str[0] == '-')
{
if(str[0]=='-')
{
sign = -1;
}
str++;
}
}
while('0'<= *str && *str <= '9' )
{
result = result*10 + (*str++ - '0');
}
return result * sign;
}
{
if(str == NULL) return 0;
int result = 0;
int sign = 1;
if( ('0'<= str[0] && str[0] <= '9') ||(str[0]=='-') || str[0]=='+')
{
if(str[0] == '+' || str[0] == '-')
{
if(str[0]=='-')
{
sign = -1;
}
str++;
}
}
while('0'<= *str && *str <= '9' )
{
result = result*10 + (*str++ - '0');
}
return result * sign;
}
后面說我沒溢出判斷:
我仔細想了想:我認為沒必有,由于我保證了傳進來的str是有意義的:
無外乎這幾種情況: {'\0'}, {'+', '\0'}, {'1', '2', '\0'} , {'a', 'b', '1', '2', '\0'},這些都應該沒有問題
,由于while('0' <= *str && *str <= '9'),等于間接就判斷了。
修改版二:
現在發現我對溢出的理解是錯誤,下面給出代碼
ps:發現linux的顏色真好看,

3、今天我才明白const char* str; 是修飾字符串不能改變的,而不是指針, 修飾常量指針的是char* const str;
那我就說說吧:
const int * const pint; //一個const指針,指向一個const成員
const int * pint; //一個非const指針, 指向一個const成員
int *pint; //一個非const指針,指向一個非const成員
int * const pint; //一個const指針,指向一個非const成員
int const * pint; //和第二個一樣, 一個非const指針, 指向一個const成員, 這個不常用