itoa() - Can the format be changed?

Started by
9 comments, last by tppramod 18 years, 11 months ago
Hi experts, Code Sample: Any_Variable = 22; char Temp_Score[5]; itoa(Any_Variable, Temp_Score,10); Draw_String(Temp_Score,10,20,14); In the above code the Draw_String function displays the value as "22" in mode 13h. Is there any way to display the values in "00022" format i.e. preceding 0's making it 5 digits. The problem with the above code is that when at any time `Any_Variable' turns 1 the function display the value as 12 i.e. the number 2 is not erased. Had the function used preceding 0', it would have displayed the value as 01, which is what is required. This is anyway possible using sprintf(), but it is slightly slower than itoa. Any help!! Thanks Pramod [Edited by - tppramod on May 15, 2005 8:53:00 AM]
Advertisement
_itoa() doesn't support padding.

The only way I could think of doing this is by doing something like the following:

char nString[6] = "00000";
int nNumber = 22;
itoa( nNumber, (nString+5) - 2, 10);

Unfortunately the 2 obviously needs to be replaced by the number of digits in nNumber, so I thought up this *ugly* beast:

itoa(number, nString+4-(((number/10 >0) > 1:0)+((number/100 >0) > 1:0)+((number/1000 >0) > 1:0)), 10);

Which works but is, quite franky hideous and inelegant and someone will probably think up a much better method!

-Scoot
IIRC:

sprintf(Temp_Score, "%05d", Any_Variable);
You can format this width sprintf function
Quote:Original post by tppramod

This is anyway possible using sprintf(), but it is slightly slower than itoa.

Pramod


-Scoot
i avoiding sprintf() only because it is slower than itoa. But i really don't know what makes it slower. May be padding? i don't know. I trying out ScootA's method, which seems to be working....

expecting some better method....

thanks

pramod
Quote:Original post by tppramod
i avoiding sprintf() only because it is slower than itoa.

Have you tried sprintf? Is the speed difference really affecting your program that much? If so, how often are you calling this? You may be able to streamline your code, and offset the speed cost of sprintf.

char *PadInt(int num){ static char MyNumber[6] = {0,0,0,0,0,0}; //Enough to hold 5 digits + NULL int NumZeros=0; memset(MyNumber,'0',5); //Set them all to # 0 if (num>=10000) //No padding required else if (num>=1000)  NumZeros=1; else if (num>=100)  NumZeros=2; else if (num>=10)  NumZeros=3; else  NumZeros=4; itoa(num,MyNumber+NumZeros,10); return MyNumber;}


Now you can do this in your loop :)

Draw_String(PadInt(Score),10,20,14);
I would not be surprised if sprintf was actually faster than the above hacks.
Quote:
sprintf


My weekly - "don't use sprintf, use snprintf" comment. Snprintf does everything sprintf does, plus gives length-safety. Have a look at Exceptional C++ style by Herb Sutter for more details.

Jim.

This topic is closed to new replies.

Advertisement