???
??? 上一篇博客講的是atoi()函數(shù)的功能及舉例,如今呢,就自己寫寫代碼(依據(jù)atoi()的功能)來表示 atoi()函數(shù)的實現(xiàn) 。我在這里先把atoi()函數(shù)的功能貼出來,也好有個參考啊~~~
??? atoi()函數(shù)的功能: 將字符串轉(zhuǎn)換成整型數(shù) ;atoi()會掃描參數(shù)nptr字符串, 跳過前面的空格字符 ,直到 遇上數(shù)字或正負號才開始做轉(zhuǎn)換 ,而 再遇到非數(shù)字或字符串時('\0')才結(jié)束轉(zhuǎn)化 ,并將結(jié)果返回( 返回轉(zhuǎn)換后的整型數(shù) )。
??? atoi()函數(shù)實現(xiàn)的代碼:
/* * name:xif * coder:xifan@2010@yahoo.cn * time:08.20.2012 * file_name:my_atoi.c * function:int my_atoi(char* pstr) */ int my_atoi(char* pstr) { int Ret_Integer = 0; int Integer_sign = 1; /* * 推斷指針是否為空 */ if(pstr == NULL) { printf("Pointer is NULL\n"); return 0; } /* * 跳過前面的空格字符 */ while(isspace(*pstr) == 0) { pstr++; } /* * 推斷正負號 * 假設(shè)是正號,指針指向下一個字符 * 假設(shè)是符號,把符號標(biāo)記為Integer_sign置-1,然后再把指針指向下一個字符 */ if(*pstr == '-') { Integer_sign = -1; } if(*pstr == '-' || *pstr == '+') { pstr++; } /* * 把數(shù)字字符串逐個轉(zhuǎn)換成整數(shù),并把最后轉(zhuǎn)換好的整數(shù)賦給Ret_Integer */ while(*pstr >= '0' && *pstr <= '9') { Ret_Integer = Ret_Integer * 10 + *pstr - '0'; pstr++; } Ret_Integer = Integer_sign * Ret_Integer; return Ret_Integer; }
??? 如今貼出執(zhí)行my_atoi()的結(jié)果,定義的主函數(shù)為:int? main? ()
int main() { char a[] = "-100"; char b[] = "456"; int c = 0; int my_atoi(char*); c = atoi(a) + atoi(b); printf("atoi(a)=%d\n",atoi(a)); printf("atoi(b)=%d\n",atoi(b)); printf("c = %d\n",c); return 0; }
??? 執(zhí)行結(jié)果:
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
