atoi()和itoa()函數詳解以及C語言實現

atoi()函數

atoi()原型:  int atoi(const char *str );c++

函數功能:把字符串轉換成整型數。windows

參數str:要進行轉換的字符串數組

返回值:每一個函數返回 int 值,此值由將輸入字符做爲數字解析而生成。 若是該輸入沒法轉換爲該類型的值,則atoi的返回值爲 0。函數

注意:使用該函數時要注意atoi返回的是int類型,注意輸入str的範圍不要超出int類型的範圍。spa

一小段代碼演示一下該函數的使用:code

#include <stdio.h> #include <stdlib.h> int main() { int a; char *ptr1 = "-12345"; a = atoi(ptr1); printf("a = %d,%d/n", a); return 0; }

 下面來用C語言進行實現該函數:blog

#include <stdio.h> #include <stdbool.h> int my_atoi(const char *src) {  int s = 0;  bool isMinus = false;  while(*src == ' ') //跳過空白符  {  src++;  }  if(*src == '+' || *src == '-')  {  if(*src == '-')  {  isMinus = true;  }  src++;  }  else if(*src < '0' || *src > '9') //若是第一位既不是符號也不是數字,直接返回異常值  {  s = 2147483647;  return s;  }  while(*src != '\0' && *src >= '0' && *src <= '9')  {  s = s * 10 + *src - '0';  src++;  }  return s * (isMinus ? -1 : 1);  } int main()  {  int num;  char *str = "a123456";  num = my_atoi(str);  printf("atoi num is: %d \r\n", num);  return 0;  } 

 itoa()函數

itoa()原型:  char *itoa( int value, char *string,int radix);內存

原型說明:字符串

輸入參數:原型

value:要轉換的數據。
string:目標字符串的地址。
radix:轉換後的進制數,能夠是10進制、16進制等,範圍必須在 2-36。

功能:將整數value 轉換成字符串存入string 指向的內存空間 ,radix 爲轉換時所用基數(保存到字符串中的數據的進制基數)。

返回值:函數返回一個指向 str,無錯誤返回。

注意:itoa不是一個標準的c函數,他是windows特有的,跨平臺寫程序,要用sprintf。

 1 #include <stdio.h> 2 #include <ctype.h> 3 4 5 //整數的各位數字加‘0’轉換爲char型並保存到字符數組中  6 int itoa(int n, char s[]) 7 { 8 int i; 9 int j; 10 int sign; 11 12 sign = n; //記錄符號 13 if(sign < 0) 14 { 15 n = -n; //變爲正數處理  16 } 17 18 i = 0; 19 do{ 20 s[i++] = n % 10 + '0'; //取下一個數字 21 }while((n /= 10) > 0); 22 23 if(sign < 0 ) 24 { 25 s[i++] = '-'; 26 s[i] = '\0'; 27 } 28 29 for(j = i; j >= 0; j-- ) 30 { 31 printf("%c \r\n", s[j]); 32 } 33 return 0; 34 } 36 int main() 37 { 38 int n; 39 char s[20]; 40 41 n = -688; 42 itoa(n, s); 43 return 0; 44 } 
相關文章
相關標籤/搜索