2

Suppose we have a matrix in C (a 2D array).

I wonder how could I print the matrix into a string in C.

For example, if I have

double M[2][2]={{1.2,3.4},{3.14,2.718}}

I want to get a string like this:

"1.200  3.400\n3.140  2.718"

which could be printed as

1.200 3.400
3.140 2.718

If print to screen, the problem will become easier because we need not consider the buffer size. However, when printing to a string, it seems hard to know how large the string buffer should be, if I want to use functions like 'sprintf'.

I searched google and stackoverflow but almost all of what I get is about how to convert string to numerical...

How to do this in C? Are there any libs?

Could you please help? Thank you!

EDIT: The 'snprintf' solution works well for the situation of just one number. But for matrix, it is supposed to use loops to go through every element. And then add a little to the string in each loop. Will this work with 'snprintf'?

6 Answers 6

1

You'll need to do this in two steps, first calculate the total size to hold the string, then allocate it and compose the string. Could be done in a function like this:

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

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a))

static char * matrix2D_to_string(const double *matrix, size_t rows, size_t columns)
{
    const char format[] = "%f";
    const char column_separator[] = "  ";
    const char row_separator[] = "\n";

    int *column_widths = NULL;
    size_t r = 0, c = 0;
    char *buffer = NULL, *p = NULL;
    size_t size = 0;

    if (!rows || ! columns) {
        errno = EINVAL;
        return NULL;
    }

    // calculate maximum width for each column
    column_widths = (int *)calloc(columns, sizeof(*column_widths));
    for (r = 0; r < rows; ++r) {
        for (c = 0; c < columns; ++c) {
            char buf[256];
            int width = sprintf(buf, format, matrix[r * columns + c]);
            if (width > column_widths[c]) {
                column_widths[c] = width;
            }
        }
    }

    // calculate total buffer size...

    // ... values
    for (c = 0; c < columns; ++c) {
        size += column_widths[c] * rows;
    }
    // ... column separators
    size += (columns - 1) * strlen(column_separator);
    // ... row separators
    size += (rows - 1) * strlen(row_separator);
    // ... nul terminator
    ++size;

    // make the string
    buffer = (char *)malloc(size);
    p = buffer;
    for (r = 0; r < rows; ++r) {
        if (r) {
            strcpy(p, row_separator);
            p += strlen(row_separator);
        }
        for (c = 0; c < columns; ++c) {
            if (c) {
                strcpy(p, column_separator);
                p += strlen(column_separator);
            }
            int width = sprintf(p, format, matrix[r * columns + c]);
            p += width;
            if (width < column_widths[c]) {
                width = column_widths[c] - width;
                memset(p, ' ', width);
                p += width;
            }
        }
    }
    *p = '\0';

    // cleanup
    free(column_widths);

    return buffer;
}

int main()
{
    double M[3][2]={{1.2,3.4},{3.14,2.718},{100.999,0.000005}};

    char *s = matrix2D_to_string((const double *)M, ARRAY_SIZE(M), ARRAY_SIZE(M[0]));

    puts(s);

    free(s);

    return 0;
}

This prints:

1.200000    3.400000
3.140000    2.718000
100.999000  0.000005
1

You may use snprintf to get buffer length you need first and then allocate and print into it:

char* PrettyPrint(const char* format, ...)
{
  va_args va;
  va_start(va, format);

  char c[1] = {};
  int len = vsnprintf(c, 1, format, va);
  char* s = malloc(len + 1);
  vsnprintf(s, len + 1, format, va);

  va_end(va);

  return s;
}
2
  • The 'snprintf' solution works well for the situation of just one number. But for matrix, it is supposed to use loops to go through every element. And then add a little to the string in each loop, will this work with 'snprintf'?
    – Roun
    May 5, 2012 at 8:24
  • You may do a bit another: char s[80]; sprintf(s, 80, "%.2f", f) and concatenate with accumulator, which you capacity you manage by reallocating: int n = strlen(s); if (accumLen + n > accumCap) { realloca and copy } strcpy(accum, s); accum += n; accumLen -= n;
    – demi
    May 5, 2012 at 8:35
0

You can start with some estimated size, and use realloc if it isn't enough.

If snprintf returns more than the remaining buffer size, it means it didn't have enough room. In this case, you should reallocate, and retry the same snprintf.

0

Its array.

considering float values.

for(i=0;i<2;i++)
{
   for(j=0;j<2;j++)
   {
       printf("%f \t",M[i][j]);
   }
   printf("\n");

}

Hope this will help you.

0
for(i=0;i<2;i++)
{
   for(j=0;j<2;j++)
   {
       printf("%f \t",M[i][j]);
   }
   printf("\\n");//Change printf("\n") as printf("\\n")
}
0
#include <stdio.h>
#include <stdlib.h>

long GetFileSize(FILE *fp){
    long fsize = 0;

    fseek(fp,0,SEEK_END);
    fsize = ftell(fp); 
    fseek(fp,0,SEEK_SET);//reset stream position!!

    return fsize;
}

char *ReadToEnd(const char *filepath){
    FILE *fp;
    long fsize;
    char *buff;

    if(NULL==(fp=fopen(filepath, "rb"))){
        perror("file cannot open at ReadToEnd\n");
        return NULL;
    }
    fsize=GetFileSize(fp);
    buff=(char*)malloc(sizeof(char)*fsize+1);
    fread(buff, sizeof(char), fsize, fp);
    fclose(fp);
    buff[fsize]='\0';

    return buff;
}

char *printStrMatrix(const char *fmt, const int col, const int row, const double* matrix ){
    FILE *fp;
    int c,r;
    char *str;

    if(NULL==(fp=fopen("printStr.tmp", "wb"))){//use tmpnam() better
        perror("temporary file cannot open at printStr\n");
        return NULL;
    }
    for(r=0;r<row;++r){
        for(c=0;c<col;++c){
            fprintf(fp, fmt, *matrix++);
            if(c != col-1)
                fprintf(fp, " ");
        }
        fprintf(fp, "\n");
    }
    fflush(fp);
    fclose(fp);
    str=ReadToEnd("printStr.tmp");
    remove("printStr.tmp");
    return str;
}

int main(void){
    double M[2][2]={{1.2,3.4},{3.14,2.718}};
    char *str;
    str=printStrMatrix("%1.3lf", 2, 2, &M[0][0]);
    printf("%s", str);
    free(str);
    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.