B00006 函数itoa()
这是一个通用的基础程序,将整型数转换为数字字符串。
其中需要用到字符串逆序转换函数reverse()。
该程序来自K&C的《C程序设计语言》一书。
程序如下:
/* itoa 带符号的整数转换字符串 */
#include <stdio.h>
#include <string.h>
void reverse(char s[])
{
    int i,j;
    int c;
    for(i=0,j=strlen(s)-1; i<j;i++,j--)
    {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}
void itoa(int n,char s[])
{
    int sign;
    if((sign=n) < 0)
        n = -n;
    int i=0; //index of s
    do
    {
        s[i] = n%10 + '0';
        i++;
    }
    while((n /= 10)>0);
    if(sign <0)
    {
        s[i++] = '-';
    }
    s[i] = '\0';
    reverse(s);
}
int main(void)
{
    char s[1024];
    itoa(-567, s);
    printf("%d %s\n", -567, s);
    itoa(1234567, s);
    printf("%d %s\n", 1234567, s);
    itoa(-1234567, s);
    printf("%d %s\n", -1234567, s);
    return 0;
}关键代码:
#include <string.h>
void reverse(char s[])
{
    int i,j;
    int c;
    for(i=0,j=strlen(s)-1; i<j;i++,j--)
    {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
    //int m = N;
}
void itoa(int n,char s[])
{
    int sign;
    if((sign=n) < 0)
        n = -n;
    int i=0; //index of s
    do
    {
        s[i] = n%10 + '0';
        i++;
    }
    while((n /= 10)>0);
    if(sign <0)
    {
        s[i++] = '-';
    }
    s[i] = '\0';
    reverse(s);
}运行结果:
-567 -567
1234567 1234567
-1234567 -1234567
 
                    
                     
                    
                 
                    
                 
                
            
         
 
         浙公网安备 33010602011771号
浙公网安备 33010602011771号