Page 1 of 1

C++ PrintInt

Posted: Thu May 15, 2003 12:44 pm
by slacker
whats the best way to write a print integer function?

i wrote my function by divinding the number by 10 in a loop and since its an integer i just subtract from the orginal.

for example the number 1234:

int temp=number/10; (temp now is 123 because its an int). then times by 10. (temp is now 1230)
print(numtoascii(number-temp)

are there any more effeciant ways of doing this printint function?

Re:C++ PrintInt

Posted: Thu May 15, 2003 1:14 pm
by df
uh.. cout << intMyInt; ??

printf("%li\n", intMyInt) still works in c++ too...

Re:C++ PrintInt

Posted: Thu May 15, 2003 6:47 pm
by slacker
i am not using standard library....

Re:C++ PrintInt

Posted: Fri May 16, 2003 12:36 am
by beyond infinity lazy

Code: Select all

int buffer;
int toconvert=12340;
char digits[32];
int position=31; //last entry in the digits array 
while(toconvert&&position){ //position may not be smaller than 0
  buffer=toconvert%10;
  digits[position]='0'+buffer;
  position--;
}
just unspool the char's stuffed in the array in reverse order by< incrementing 'position' in your printf-'function'

Re:C++ PrintInt

Posted: Fri May 16, 2003 1:39 am
by Tim
You need to divide toconvert by 10 on each pass through the loop.

Re:C++ PrintInt

Posted: Fri May 16, 2003 3:00 am
by distantvoices
alright, 've forgotten that. Some small but essential thing. should do this more carefully and look before i type instead of doing it fully by heart.