itoa與sprintf函數 linux c 字串處理函數

來源:互聯網
上載者:User
itoa與sprintf函數 linux c 字串處理函數
itoa函數及atoi函數,c語言提供了幾個標準庫函數,可以將任意類型(整型、長整型、浮點型等)的數字轉換為字元

串。以下是用itoa()函數將整數轉 換為字串的一個例子:

# include <stdio.h>
# include <stdlib.h>

void main (void)
{
int num = 100;
char str[25];
itoa(num, str, 10);
printf("The number 'num' is %d and the string 'str' is %s. /n" ,
num, str);
}

itoa()函數有3個參數:第一個參數是要轉換的數字,第二個參數是要寫入轉換結果的目標字串,第三個參數是轉移數字時所用

的基數。在上例中,轉換基數為10。10:十進位;2:二進位...

itoa並不是一個標準的C函數,它是Windows特有的,如果要寫跨平台的程式,請用sprintf。
是Windows平台下擴充的,標準庫中有sprintf,功能比這個更強,用法跟printf類似:

char str[255];
sprintf(str, "%x", 100); //將100轉為16進位表示的字串。

下列函數可以將整數轉換為字串:
----------------------------------------------------------
函數名 作 用
----------------------------------------------------------
itoa() 將整型值轉換為字串
ltoa() 將長整型值轉換為字串
ultoa() 將無符號長整型值轉換為字串


一 atoi 把字串轉換成整型數

常式序:

#include <ctype.h>
#include <stdio.h>
int atoi (char s[]);

int main(void )
{

char s[100];

gets(s);

printf("integer=%d/n",atoi(s));
return 0;
}
int atoi (char s[])
{
int i,n,sign;

for(i=0;isspace(s[i]);i++)//跳過空白符
;
sign=(s[i]=='-')?-1:1;
if(s[i]=='+'||s[i]==' -')//跳過符號
i++;
for(n=0;isdigit(s[i]);i++)
n=10*n+(s[i]-'0');//將數字字元轉換成整形數字
return sign *n;

}

二 itoa 把一整數轉換為字串

常式序:

#include <ctype.h>
#include <stdio.h>
void itoa (int n,char s[]);
//atoi 函數:將s轉換為整形數
int main(void )
{
int n;
char s[100];

printf("Input n:/n");
scanf("%d",&n);

printf("the string : /n");
itoa (n,s);
return 0;
}
void itoa (int n,char s[])
{
int i,j,sign;

if((sign=n)<0)//記錄符號
n=-n;//使n成為正數
i=0;
do{
s[i++]=n%10+'0';//取下一個數字
}while ((n/=10)>0);//刪除該數字

if(sign<0)
s[i++]='-';
s[i]='/0';
for(j=i;j>=0;j--)//產生的數字是逆序的,所以要逆序輸出
printf("%c",s[j]);

}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.