簡體   English   中英

如何將函數內部的printf輸出輸出到c中的主程序

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

我有一個功能,可以打印很多printf語句,輸出的行數不是固定的。 我需要將所有在myFun打印的myFun移至主要功能,並將其用於其他目的。 有人可以指導如何做嗎?

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

您可以嘗試將字符串保存到數組中,然后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