如何打印在同一行上所有的数组元素? [英] How do I print all array elements on the same line?
本文介绍了如何打印在同一行上所有的数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不得不删除所有code。什么我寻找是如何的sprintf数组的所有元素在同一直线上。
I had to delete all the code. What I' looking is how to sprintf all elements of an array in the same line.
该显示器具有2行,我需要打印阵列10,24,32,40,51,.....第一线
和10,51 .....第二行
The display has 2 lines, I need to print the array 10,24,32,40,51, .....first line and 10,51 .....second line
推荐答案
样品
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *join(int n, const int array[n], const char *format, const char *sep){
if(!format)
format = "%d";
if(!sep)
sep = ", ";
size_t len = strlen(sep)*(n-1)+1;//+1 for EOS
int i;
for(i=0;i<n;++i)
len += snprintf(NULL, 0, format, array[i]);
char *result = malloc(len);
if(!result)return NULL;
size_t pos = 0;
for(i=0;i<n;++i){
pos += sprintf(result + pos, format, array[i]);
if(i != n-1)
pos += sprintf(result + pos, "%s", sep);
}
return result;
}
int main (void){
int array[][5]={{10,24,32,40,51},{10,1,99,77,88}};
int row_size = sizeof(array)/sizeof(array[0]);
int col_size = sizeof(array[0])/sizeof(int);
char *join_str;
int i;
for(i=0;i<row_size;++i){
char *join_str = join(col_size, array[i], "%2d", ", ");
printf("%s\n", join_str);
free(join_str);
}
return 0;
}
这篇关于如何打印在同一行上所有的数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文