基于atoi()與itoa()函數(shù)的內(nèi)部實(shí)現(xiàn)方法詳解
更新時(shí)間:2013年05月24日 12:00:11 作者:
本篇文章是對(duì)atoi()與itoa()函數(shù)的內(nèi)部實(shí)現(xiàn)方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下
C語言提供了幾個(gè)標(biāo)準(zhǔn)庫函數(shù),可以將任意類型(整型、長整型、浮點(diǎn)型等)的數(shù)字轉(zhuǎn)換為字符串。以下是用itoa()函數(shù)將整數(shù)轉(zhuǎn) 換為字符串的一個(gè)例子:
atoi 把字符串轉(zhuǎn)換成整型數(shù)
itoa 把一整數(shù)轉(zhuǎn)換為字符串
#include "stdio.h"
#include "ctype.h"
#include "stdlib.h"
/*
Converts a character string into an int or long
將一個(gè)字符串轉(zhuǎn)化為整數(shù)
*/
int my_atoi(char s[])
{
int i,n,sign;
for(i=0;isspace(s[i]);i++); //跳過空白
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]==' -') //跳過符號(hào)位
i++;
for(n=0;isdigit(s[i]);i++)
n=10*n+(s[i]-'0'); //將數(shù)字字符轉(zhuǎn)換成整形數(shù)字
return sign*n;
}
/*
Converts an int or long into a character string
將一個(gè)整數(shù)轉(zhuǎn)化為字符串
*/
void my_itoa(int n,char s[])
{
int i,j,sign;
if((sign=n)<0) //記錄符號(hào)
n=-n; //使n成為正數(shù)
i=0;
do{
s[i++]=n%10+'0'; //取下一個(gè)數(shù)字
}while((n/=10)>0); //循環(huán)相除
if(sign<0)
s[i++]='-';
s[i]='\0';
for(j=i-1;j>=0;j--) //生成的數(shù)字是逆序的,所以要逆序輸出
printf("%c",s[j]);
}
void main()
{
int n;
char str[100];
my_itoa(-123,str);
printf("\n");
printf("%d\n",my_atoi("123"));
system("pause");
}
atoi 把字符串轉(zhuǎn)換成整型數(shù)
itoa 把一整數(shù)轉(zhuǎn)換為字符串
復(fù)制代碼 代碼如下:
#include "stdio.h"
#include "ctype.h"
#include "stdlib.h"
/*
Converts a character string into an int or long
將一個(gè)字符串轉(zhuǎn)化為整數(shù)
*/
int my_atoi(char s[])
{
int i,n,sign;
for(i=0;isspace(s[i]);i++); //跳過空白
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]==' -') //跳過符號(hào)位
i++;
for(n=0;isdigit(s[i]);i++)
n=10*n+(s[i]-'0'); //將數(shù)字字符轉(zhuǎn)換成整形數(shù)字
return sign*n;
}
/*
Converts an int or long into a character string
將一個(gè)整數(shù)轉(zhuǎn)化為字符串
*/
void my_itoa(int n,char s[])
{
int i,j,sign;
if((sign=n)<0) //記錄符號(hào)
n=-n; //使n成為正數(shù)
i=0;
do{
s[i++]=n%10+'0'; //取下一個(gè)數(shù)字
}while((n/=10)>0); //循環(huán)相除
if(sign<0)
s[i++]='-';
s[i]='\0';
for(j=i-1;j>=0;j--) //生成的數(shù)字是逆序的,所以要逆序輸出
printf("%c",s[j]);
}
void main()
{
int n;
char str[100];
my_itoa(-123,str);
printf("\n");
printf("%d\n",my_atoi("123"));
system("pause");
}
相關(guān)文章
C++算法實(shí)現(xiàn)leetcode 1252奇數(shù)值單元格數(shù)目
這篇文章為大家主要介紹了C++實(shí)現(xiàn)leetcode 1252奇數(shù)值單元格的數(shù)目題解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
VS2022連接sqlserver數(shù)據(jù)庫教程
本文主要介紹了VS2022連接sqlserver數(shù)據(jù)庫教程,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
C++實(shí)踐排序函數(shù)模板項(xiàng)目的參考方法
今天小編就為大家分享一篇關(guān)于C++實(shí)踐排序函數(shù)模板項(xiàng)目的參考方法,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧2019-02-02
如何基于C語言socket編程實(shí)現(xiàn)TCP通信
本文介紹了如何基于C語言socket編程實(shí)現(xiàn)TCP通信,下面小編來簡單介紹下2019-05-05
C語言動(dòng)態(tài)數(shù)組的使用實(shí)現(xiàn)代碼
這篇文章主要介紹了C語言動(dòng)態(tài)數(shù)組的使用實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-01-01

