#include <stdio.h>
void itoa(int ,char *);
void reverse(char *);
/*itoa 函數: 將數字轉換成字符串並保存到S中*/
void itoa(int n, char s[])
{
int i,sign;
if((sign = n) < 0)
n = -n;
i = 0;
do
{
s[i++] = n % 10 + '0';
}while((n /= 10) > 0);
if(sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/*reverse 函數:字符串反轉(指針方法不安全)*/
void reverse(char *s)
{
int len = strlen(s);
char *ptr1,*ptr2;
ptr1 = s;
ptr2 = s + len - 1;
while(ptr1 != ptr2)
{
char temp;
temp = *ptr1;
*ptr1 = *ptr2;
*ptr2 = temp;
ptr1++;
if(ptr1 == ptr2)
break;
else
ptr2--;
}
}
/*《The C programming language(second edition)》中實現int型轉字符串練習*/
int main()
{ int a;
char s[20];
printf("please input a int :\n");
scanf("%d",&a);
itoa(a,s);
printf("The int is %s\n",s);
return 0;
}
C語言整數轉字符串(itoa()函數)小練習
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.