SD1990
SD1990

Reputation: 808

How store a number starting with 0 in C

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

Answers (4)

David Heffernan
David Heffernan

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.

  1. Store the string as your master data.
  2. Whenever you need to perform arithmetic, convert from string to integer.
  3. When the arithmetic is complete, convert back to string and store.

Upvotes: 8

Frerich Raabe
Frerich Raabe

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

ahmet
ahmet

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

NPE
NPE

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

Related Questions