0

The concept is very similar to this Add zero-padding to a string but it's a question from c# NOT C.

While you can add a zero padding in printf like this printf("%4d", number)

How can I have a zero padding to a string? ex:

char *file_frame = "shots";
strcat(file_frame, "%3d", number); // It's my attempt to solve it. I know it's wrong

so that I would get shots000 from file_frame

3 Answers3

1

You need to use sprintf

sprintf(file_frame, "%04d", 34);

The 0 indicates what you are padding with and the 4 shows the length of the integer number.


Also you should be using mutable array as below.

char *file_frame = "shots"; --> char file_frame[100] = "shots";
kiran Biradar
  • 12,700
  • 3
  • 19
  • 44
1

First you need some space to store the string. Then you "print" into this string:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    char file_name[8 + 1]; // "shots###" is 8 characters, plus 1 for end-of-string marker '\0'
    int number = 23;
    sprintf(file_name, "shots%03d", number);

    printf("\"%s\"\n", file_name);
    return EXIT_SUCCESS;
}

You can combine literal parts with formatting parts in any *printf() function.

the busybee
  • 10,755
  • 3
  • 13
  • 30
-1

Well, this is the workaround I did: -

char output[9];
char buffer[9];

itoa(num, output, 2);
int i=0;
for (i=0; i<(8-strlen(output));i++) {
    buffer[i]='0';
}
for(int j=0;j<strlen(output);j++){
    buffer[i] = output[j];
    i++;
}

Input:-

num = 10

Output: -

buffer = 00001010
Rahul
  • 205
  • 2
  • 8