C++ PrintInt

Programming, for all ages and all languages.
Post Reply
slacker

C++ PrintInt

Post 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?
User avatar
df
Member
Member
Posts: 1076
Joined: Fri Oct 22, 2004 11:00 pm
Contact:

Re:C++ PrintInt

Post by df »

uh.. cout << intMyInt; ??

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

Re:C++ PrintInt

Post by slacker »

i am not using standard library....
beyond infinity lazy

Re:C++ PrintInt

Post 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'
Tim

Re:C++ PrintInt

Post by Tim »

You need to divide toconvert by 10 on each pass through the loop.
distantvoices
Member
Member
Posts: 1600
Joined: Wed Oct 18, 2006 11:59 am
Location: Vienna/Austria
Contact:

Re:C++ PrintInt

Post 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.
... the osdever formerly known as beyond infinity ...
BlueillusionOS iso image
Post Reply