How to transform an array of integers into a string with C

1 Answer

0 votes
#include <stdio.h>

int transform_ints_to_string(int const* arr, int arr_size, char* buf, int buf_size) {
    int total_size = 0;

    for (; arr_size; arr_size--) {
        int length = snprintf(buf, buf_size, "%5d", *arr++);

        if (length >= buf_size) {
            return -1;
        }

        total_size += length;
        buf += length;
        buf_size -= length;
    }

    return total_size;
}

int main()
{
    char buf[128] = "";
    int arr[] = { 56, 8, 12, 908, 1046 };
    int arr_size = sizeof(arr) / sizeof(arr[0]);

    if (transform_ints_to_string(arr, arr_size, buf, sizeof buf) == -1) {
        puts("not enough space in buf");
    }
    else {
        printf("%s\n", buf);
    }

    return 0;
}



/*
run:

   56    8   12  908 1046

*/

 



answered Jul 31, 2024 by avibootz
...