假设我们有一个 C 语言矩阵(二维数组)。
我想知道如何将矩阵打印到 C 中的字符串中。
例如,如果我有
double M[2][2]={{1.2,3.4},{3.14,2.718}}
我想得到这样的字符串:
"1.200 3.400\n3.140 2.718"
可以打印为
1.200 3.400
3.140 2.718
如果打印到屏幕,问题会变得更容易,因为我们不需要考虑缓冲区大小。但是,当打印到字符串时,如果我想使用“sprintf”等函数,似乎很难知道字符串缓冲区应该有多大。
我搜索了 google 和 stackoverflow,但我得到的几乎所有内容都是关于如何将字符串转换为数字......
如何用 C 语言做到这一点?有库吗?
你能帮忙吗?谢谢!
编辑: “snprintf”解决方案非常适合只有一个数字的情况。 但对于矩阵,应该使用循环来遍历每个元素。 然后在每个循环中向字符串添加一点。这可以与“snprintf”一起使用吗?
最佳答案
您需要分两步执行此操作,首先计算容纳字符串的总大小,然后分配它并组成字符串。可以在这样的函数中完成:
#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;
}
打印:
1.200000 3.400000
3.140000 2.718000
100.999000 0.000005
关于c - 如何在C中将数字矩阵打印成字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10459919/