Printing a number without using * printf

Is it possible to print (before stdout or a file) a number ( int , float , double , long , etc.) without actually using any of the functions *printf ( printf , fprintf , sprintf , snprintf , vsprintf , ...)?

+6
c
source share
5 answers

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

itoa() implementation from C programming language, 2nd edition - Kernigan and Ritchie p. 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); } 
+7
source share

Well, it’s not difficult to do for integers, but the task is more complicated for floating point numbers, and someone has already placed a pointer to explain this. 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); } 
+3
source share

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

+2
source share

this will lead to the 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)); } 
+2
source share

I guess most people come across this question because they wrote their own sequential tx functions and need to print some numbers. You will need to modify the putc call to match 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 the number in reverse order.

0
source share

All Articles