#include<stdarg.h>
#include <strings.h>
void print_arrays(int nrow,char *prspec, ...){
//print arrays of same length to the console
// prpec forma stringas as in printf()
// narg numer of arrays passed to function,
//picnt pdcnt counters for number of int and double array pointers
// pi pd arrays of pointers to arrays
cout<<"print arrays "<<endl;
int i,j,narg = 0,picnt = 0,pdcnt = 0;
int * pi[20];
double *pd[20];
//--------------------------------------
//split format string into substrigs for printf()
char fdel[2] = " "; //split delimiter
char pfmt[10][10];
char * token = strtok(prspec,fdel);
while( token != NULL ) {
strcpy(pfmt[narg++],token);
//printf( " %s\n", token ); //printing each token
token = strtok(NULL, fdel);
}
//-------------------------------------
// make var_args format string
int nfmt = 100;
char *fmt = new char[nfmt];
for(i=0;i<nfmt;i++)fmt[i] = '\0'; //null the array so strcat() starts at fmt[0]
for(i=0;i<narg;i++){
if(strchr(pfmt[i],'d') != NULL)strcat(fmt," d");
if(strchr(pfmt[i],'f') != NULL)strcat(fmt," f");
if(strchr(pfmt[i],'e') != NULL)strcat(fmt," f");
}
//cout<<"fmt "<<fmt<<endl;
//--------------------------------------
//get pointers to arrays
va_list args;
va_start(args, fmt);
while (*fmt != '\0') {
if(*fmt == 'd')pi[picnt++] = va_arg(args, int*);
if(*fmt == 'f')pd[pdcnt++] = va_arg(args, double*);
if(*fmt == 'e')pd[pdcnt++] = va_arg(args, double*);
//cout<<*fmt;
++fmt;
}//while
//cout<<endl;
va_end(args);
//printf("counts %d %d\n",picnt,pdcnt);
//--------------------------------------------
//print arrays
for(i = 0;i<nrow;i++){
picnt = 0;
pdcnt = 0;
for(j=0;j<narg;j++){
if(strchr(pfmt[j],'d') != NULL)printf(pfmt[j],*(pi[picnt++]+i));
if(strchr(pfmt[j],'f') != NULL)printf(pfmt[j],*(pd[pdcnt++]+i));
if(strchr(pfmt[j],'e') != NULL)printf(pfmt[j],*(pd[pdcnt++]+i));
if(j<narg-1)printf("\t"); //no tab after last column
}//for j
printf("\n");
}//for i
}//print_arrays()
int main(){
int n = 4;
int xi2[n] = {10,20,30,40},xi1[n] = {1,2,3,4};
double xd1[n] = {1.1,2.2,3.3,4.1};
double xd2[n] = {10.1,20.2,30.3,40.4};
char fmt[] = "%10d %5.3f %5d %1.2e";
print_arrays(n,fmt,xi1,xd1,xi2,xd2);
return 0;
}