开发者

Printing a number without using *printf

开发者 https://www.devze.com 2023-02-21 11:59 出处:网络
Is it possible to print (to stdout, or a file) an number (int, float, double, long, etc.) without actuall开发者_如何转开发y using any of the *printf functions (printf, fprintf, sprintf, snprintf, vspr

Is it possible to print (to stdout, or a file) an number (int, float, double, long, etc.) without actuall开发者_如何转开发y using any of the *printf functions (printf, fprintf, sprintf, snprintf, vsprintf, …)?


If your libc contains an itoa() function, you can use it to convert an integer to a string.
Otherwise you'll have to write the code to convert a number to a string yourself.

itoa() implementation from C Programming Language, 2nd Edition - Kernighan and Ritchie page 64:

/* itoa: convert n to characters in s */
void itoa(int n, char s[])
{
   int i, sign;

   if ((sign = n) < 0)  /* record sign */
      n = -n;           /* make n positive */
   i = 0;
   do {  /* generate digits in reverse order */
      s[i++] = n % 10 + '0';  /* get next digit */
   } while ((n /= 10) > 0);   /* delete it */
   if (sign < 0)
      s[i++] = '-';
   s[i] = '\0';
   reverse(s);
}


Well, its not hard to do for integers, but the job is a fair bit more complicated for floating point numbers, and someone has already posted a pointer to an explanation for that. For integers, you can do something like this:

void iprint(int n)
  { 
    if( n > 9 )
      { int a = n / 10;

        n -= 10 * a;
        iprint(a);
      }
    putchar('0'+n);
  }


this would result correct order:

void print_int(int num){
    int a = num;

    if (num < 0)
    {
       putc('-');
       num = -num;
    }

    if (num > 9) print_int(num/10);

    putc('0'+ (a%10));
 }


Simply use the write() function and format the output yourself.


Based on @Whitham Reeve II answer given above, here is a better version:

No need for the 'a' int variable to hold 'num' ; Since each recursive call will have a separate copy of 'num' value (i.e. call by value). Also it seems some compilers require you to pass also "stdout" as 2nd parameter to dump chars on screen.

void print_int(int num){
    if (num < 0)
    {
       putc('-', stdout);
       num = -num;
    }

    if (num > 9) print_int(num/10);

    putc('0'+ (num%10), stdout);
 }


I assume most people that come across this question because they have written their own serial tx functions and need to print some numbers. You will need to modify the putc call to fit with your setup.

void print_int(int num)
{
    if (num < 0)
    {
        putc('-');
        num = -num;
    }
    else if (num == 0)
    {
        putc('0');
        return;
    }   
    while (num != 0)
    {
        putc ('0'+ (num%10));
        num /= 10;
    }
}

This will print a number in reverse.

0

精彩评论

暂无评论...
验证码 换一张
取 消