I have a function which print lot of printf
statements, number of lines as output is not fixed. I need to get all the lines which are getting printed in myFun
to the main function and used them for some other purpose. Can someone please guide how to do that ?
#include<stdio.h>
int myFun(char* name){
printf("myFun: this is important line too\n");
printf("myFun: my name is %s\n",name);
printf("myFun: this is a important line needed in main, genrated from some function called inside myFun\n");
}
int main(){
printf("this is main and now calling myFun\n");
myFun("monk");
//how can I get all the output of all three printf statements done inside myFun to the main function ?
return 0;
}
You could try saving the strings into an array, and return
ing the whole array:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **Func(char *name)
{
int numOfOutputs = 3;
numOfOutputs++; //Append an extra null byte to the end so we know when it ends
int maximumStringSize = 100;
char **final = (char **)malloc(numOfOutputs * sizeof(char *));
for (int i = 0; i < numOfOutputs; i++)
final[i] = (char *)malloc(maximumStringSize * sizeof(char));
strcpy(final[0], "myFun: this is important line too\n");
sprintf(final[1], "myFun: my name is %s\n", name);
strcpy(final[2], "myFun: this is a important line needed in main, genrated from some function called inside myFun\n");
//Final member assigned as NULL to indicate end
final[3] = NULL;
return final;
}
int main()
{
printf("this is main and now calling myFun\n");
char **result = Func("monk");
//Print result, check for ending member with the nullbyte we added
for(int i = 0 ; result[i] != NULL; i++)
printf("For i = %d, string is -> %s", i, result[i]);
//Don't forget to free with something like this:
for(int i = 0 ; result[i] != NULL; i++)
free(result[i]);
free(result);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.