atoi()函數
atoi()原型: int atoi(const char *str );
函數功能:把字符串轉換成整型數。
參數str:要進行轉換的字符串
返回值:每個函數返回 int 值,此值由將輸入字符作為數字解析而生成。 如果該輸入無法轉換為該類型的值,則atoi的返回值為 0。
注意:使用該函數時要注意atoi返回的是int類型,注意輸入str的范圍不要超出int類型的范圍。
一小段代碼演示一下該函數的使用:
#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語言進行實現該函數:
#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 }
