using sprintf() with 0's

M

markww

Hi,

Is there a way to use sprintf() to put a number of zeros before a
number, like:

sprintf(szBuffer, "%i", 7);

"007";

I have a list of numbers I want to sort that are text based, and I want
to put zeros before some so they get sorted in order like:

007
008
009
010
011
012

Thanks
 
B

billy

How about sprintf (szBuffer, "%03i", 7)?

The leading 0 of "%03i" means to print 0 in front of the number; 3
means the field width is 3.
 
W

wittempj

markww said:
Hi,

Is there a way to use sprintf() to put a number of zeros before a
number, like:

sprintf(szBuffer, "%i", 7);

"007";

I have a list of numbers I want to sort that are text based, and I want
to put zeros before some so they get sorted in order like:

007
008
009
010
011
012

Thanks

this padds it with zeros, and lenghth 3:

sprintf(szBuffer, "%03i", 7);
 
J

Jim Langston

markww said:
Hi,

Is there a way to use sprintf() to put a number of zeros before a
number, like:

sprintf(szBuffer, "%i", 7);

"007";

I have a list of numbers I want to sort that are text based, and I want
to put zeros before some so they get sorted in order like:

007
008
009
010
011
012

Thanks

You could do as others said, but I would probably just use stringstring to
convert it to an int and sort that anyway. Either way you're going to need
a temporary to sort on (in your case szBuffer, in my case an int). This
also has the advantage of being able to sort arbitrary sized numbers. What
happens when you get to 1000?
 
J

Jim Langston

Victor Bazarov said:
Jim said:
[..] I would probably just use
stringstring to [..]

"stringstring"?

V

You know how many times I type std::stringstring in a program and get a
syntax error? Just about every time I use it actually.

Of course I meant std::stringstream
 
O

Old Wolf

markww said:
That is some hot gravy, thanks guys.

Bear in mind that the 3 doesn't limit the field width, eg:

sprintf(buf, "%03i", 1234);

will still write "1234". So buf needs to be big enough for the
biggest possible integer (including 0 terminator).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top