Printing To Screen: Difference between revisions

Jump to navigation Jump to search
→‎Printing Integers: '''If''' we provide example code, we could just as well go the full distance. ;-)
[unchecked revision][unchecked revision]
(→‎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):
Here is some sample code:
 
<source lang="c">
char * itoa( int value, char * str, int base )
void printint(int val) //Change the declaration to suit you
{
char tmp[9]* = {0}rc;
intchar temp* = valptr;
intchar n* = 1low;
// Check for supported base.
while(temp != 0)
if ( base < 2 || base > 36 )
{
temp*str /= 10'\0';
int intChar = temp % 10; //Set character to least sig bit
n++return str;
tmp[9-n] = (char)(intChar+0x30); //ASCII offset for digits
temp /= 10;
n++;
}
rc = ptr = n--str;
n--; //Algorithm will leave n pointing to a 0
// Set '-' for negative decimals.
while(n!=0)
if ( value < 0 && base == 10 )
{
putc(tmp[9*ptr++ = '-n])';
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;
} while (temp !=value 0);
// Terminating the string.
*ptr-- = '\0';
// Invert the numbers.
while (n!=0 low < ptr )
{
char tmp = *low;
*low++ = *ptr;
*ptr-- = tmp;
}
return rc;
}
</source>
448

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.

Navigation menu