Printing To Screen: Difference between revisions
[unchecked revision] | [unchecked revision] |
Content deleted Content added
→Printing Integers: Added C++ function |
→Printing Integers: '''If''' we provide example code, we could just as well go the full distance. ;-) |
||
Line 59:
digits to be displayed are '1','2','3','4' ... if you know the numerical value of number%10, you simply have to add this to the character '0' to have the correct character (e.g. '0'+4 == '4')
Here is an example implementation of the itoa() function (which is not standard, but provided by many libraries):
<source lang="c">
char * itoa( int value, char * str, int base )
{
char
// Check for supported base.
while(temp != 0)▼
if ( base < 2 || base > 36 )
{
▲ temp /= 10;
▲ n++;
}
// Set '-' for negative decimals.
while(n!=0)▼
if ( value < 0 && base == 10 )
{
▲ n--;
}
// Remember where the numbers start.
low = ptr;
// The actual conversion.
do
{
// Modulo is negative for negative value. This trick makes abs() unnecessary.
*ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + value % base];
value /= base;
// Terminating the string.
*ptr-- = '\0';
// Invert the numbers.
{
char tmp = *low;
*low++ = *ptr;
*ptr-- = tmp;
}
return rc;
}
</source>
|