Reputation: 808
Id just thought id ask this question to see whether it can actually be done.
if i want to store a number like "00000000000001", What would be the best way? bearing in mind that this also has to be incrememted on a regular basis.
Im thinking either there is a way to do this with the integer or i have to convert to a char array somewhere along the line. This would be fine but its a pain to try and increment a string.
Upvotes: 1
Views: 4025
Reputation: 612993
I would store it as an integer and only convert to the formatted version with leading zeros on demand when you need to produce output, for example with printf
, sprintf
etc.
It's far easier that way than storing a string and trying to perform arithmetic on strings. Not least because you have extra formatting requirements about your strings.
If for some reason it is awkward to store an integer as your master data do it like this.
Upvotes: 8
Reputation: 94329
You should simply store the number using an appropriate type (say, unsigned int
), so that doing operations like 'increment by one' are easy - only bother worrying about leading zeros when displaying the number.
sprintf
can actually do this for you:
unsigned int i = 1;
char buffer[64];
sprintf( buf, "%014u", i );
This prints '00000000000001'.
Upvotes: 7
Reputation: 5005
#include <stdlib.h> // for itoa() call
#include <stdio.h> // for printf() call
int main() {
int num = 123;
char buf[5];
// convert 123 to string [buf]
itoa(num, buf, 10);
// print our string
printf("%s\n", buf);
return 0;
}
Upvotes: 0
Reputation: 500367
You could store it in a integer variable (provided there's an integer type that's wide enough for your needs). When printing, simply format the number to have the correct number of leading zeros.
Upvotes: 1