How to add N zeros to an empty string in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* addToEmptyStr(char* pad, size_t n) {
    char* str = calloc(n + 1, sizeof(char));

    while (strlen(str) < n) {
        strcat(str, pad);
    }

    return str;
}

int main() {
    int n = 4;

    char* empty_string = addToEmptyStr("0", n);

    printf("%s\n", empty_string);

    free(empty_string);

    return 0;
}





/*
run:

0000

*/

 



answered May 26, 2024 by avibootz

Related questions

2 answers 133 views
1 answer 126 views
1 answer 121 views
1 answer 128 views
2 answers 144 views
1 answer 135 views
2 answers 124 views
124 views asked May 26, 2024 by avibootz
...