Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

zero padding numerical datatypes

Status
Not open for further replies.

kmm64

Technical User
May 4, 2004
8
US
Hi all,
Quick question, is there a way to pad int's or any other numeric datatype with leading zeros like this:

int a = 25;
int b = 003;

int c = a + b; // value of c is now 028

I'm not talking about printing with padded zeroes but actually doing computations with padded zeroes. I'm working on a part of a project that grabs files with the same name but with different id numbers:

textReport1.txt
textReport2.txt
textReport14.txt
textReport17.txt

But the problem is that the files are in file order rather than numeric order. When actually traversing the file list above the open file dialogue box wouldn't list them as such but as:

textReport1.txt
textReport14.txt
textReport17.txt
textReport2.txt

These files are created by another program that is out of my hands so I can't pad the id number with zeros when actually creating the file names.

So I would like to be able to grab the id numbers, pad them with zeros and make the necessary comparisions to find out which file should be opened next in numerical order.

Any help or insight will be greatly appreciated.
Thanks a million.
 
How about something like this:

Code:
for (i=1;i<MAX;i++) {
  sprintf(filename,"textReport%d.txt",i);
  f=fopen(filename,"r");
  /* read in file data */
  fclose(f);
}
 
Try this when writingfile name:
sprintf(filename,"textReport%3d.txt",i);


Ion Filipski
1c.bmp
 
Thanks alot for the replies. Works perfectly.
 
Be aware that placing a leading zero in front of a value can make it octal. (I am tapping an old memory bank but I believe this bit me in the butt about 5 yrs ago)

Matt
 
Yeah, I read about that but as of now I have come up with several ways to overcome my problem. Now trying to figure out which is most optimal.

Thanks for the advice.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top