简体   繁体   English

如何将函数内部的printf输出输出到c中的主程序

[英]how to get output of printf inside the function to the main program in c

I have a function which print lot of printf statements, number of lines as output is not fixed. 我有一个功能,可以打印很多printf语句,输出的行数不是固定的。 I need to get all the lines which are getting printed in myFun to the main function and used them for some other purpose. 我需要将所有在myFun打印的myFun移至主要功能,并将其用于其他目的。 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: 您可以尝试将字符串保存到数组中,然后return整个数组:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM