相關知識:
頭文件:#include <stdlib.h>
atoi() 函數用來將字符串轉換成整數(int),其原型爲:
int atoi (const char * str);
【函數說明】atoi() 函數會掃描參數 str 字符串,跳過前面的空白字符(例如空格,tab縮進等,可以通過 isspace() 函數來檢測),直到遇上數字或正負符號纔開始做轉換,而再遇到非數字或字符串結束時('\0')才結束轉換,並將結果返回。
【返回值】返回轉換後的整型數;如果 str 不能轉換成 int 或者 str 爲空字符串,那麼將返回 0。
程序如下:
#include <stdio.h>
#include <stdlib.h>
int myatoi(const char *str)
{
int flag = 1;
int result = 0;
if(str == NULL)
return 0;
while(*str == ' ' || *str == '\t')
str++;
if(*str == '-')
{
flag = -1;
str++;
}
while(*str != '\0')
{
if(*str >= 0 && *str <= '9')
result = result*10 + (*str - '0');
else
{
break;
}
str++;
}
return result * flag;
}
int main()
{
char *s1 = "123jie";
char *s2 = "-323dkr";
printf("result = %d\n",myatoi(s1));
printf("result = %d\n",myatoi(s2));
return 0;
}
運行結果如圖所示: