在 C 语言的 fprintf 语法中调用函数

Calling a function within fprintf syntax in C language

我正在尝试将我的字符串输出打印到一个单独的文件中。我现在 运行 遇到的问题是我的代码带有一组字符串的函数,该函数在我的列下方添加虚线(纯粹是装饰品)。如何在我的 fprintf 代码中调用此函数?

#include <stdio.h>
/* function for the dash-line separators*/
void
dashes (void)
{
printf ("  ----           -----        --------------------     --------------\n");
}
/* end of function definition */

/* main program */
#include <stdio.h>
#include <string.h>
int
main (void)
{
FILE *data_File;
FILE *lake_File;
FILE *beach_File;
FILE *ecoli_Report;
char fileName[10], lake_Table[15],beach_Table[15];  /*.txt file names */

char province[30] = "";         /*variable for the file Lake Table.txt*/
char beach[20]="",beach1[20];   /*variable for the file Beach Table.txt*/
char decision[15] = "CLOSE BEACH";

int lake_data=0,lake_x=0, beach_x=0, nr_tests=0;    /* variables for the file july08.txt */
int province_data=0,prv_x=0;        /* variables for the file Lake Table.txt */
int beach_data=0,bch_x=0;           /* variables for the file Beach Table.txt*/

int j;
double sum, avg_x, ecoli_lvl;
printf ("Which month would you like a summary of? \nType month followed by date (i.e: july05): ");
gets(fileName);
/*Opening the files needed for the program*/
data_File = fopen (fileName, "r");
lake_File = fopen ("Lake Table.txt", "r");
beach_File = fopen ("Beach Table.txt", "r");
ecoli_Report = fopen ("Lake's Ecoli Levels.txt", "w");

fprintf (ecoli_Report,"\n  Lake           Beach          Average E-Coli Level     Recommendation\n");
fprintf (ecoli_Report,"%c",dashes());

您需要更改破折号函数以获取指向要用于输出的文件流的指针。然后在函数内使用 fprintf 而不是 printf。

或者,您可以使用破折号 return 字符串 (char *),然后使用 fprintf - 请注意您需要 %s 而不是当前编码的 %c

dashes() is void returning function 你怎么得到这一行?

 fprintf (ecoli_Report,"%c",dashes());

如果你需要打印文件中的行,制作原型并像这样调用,

 void dashes(FILE *fp){
    fprintf(fp,"------------------\n");
 }

删除此行。

 fprintf (ecoli_Report,"%c",dashes());

然后把调用改成这样,

 dashes(ecoli_Report);

或者干脆这样做,

 fprintf(ecoli_Report,"----------------");

向您的函数添加一个 FILE 参数并将文件句柄传递给它,并在函数内部使用 fprintf。

或者,您可以使用破折号 return 字符数组而不是 void。

如果您按如下方式重新编码您的函数:

char *strdashes (void) {
    return "  ----           -----        --------------------     --------------";
}
void dashes (void) {
    puts (strdashes());
}

那么您可以任意使用它。调用 dashes() 仍会将字符串输出到标准输出,后跟一个换行符,这相当于:

printf ("%s\n", strdashes());

或者, 您可以执行 任意 操作 (a) strdashes()(当然除了尝试将其更改为字符串文字):

fprintf (errorLog, "%s: %s\n", datetime(), strdashes());

(a) 比如写入一个不同的文件句柄,用strlen()得到它的长度,用 strcpy() 复制它,你可能想用 = 替换所有 - 个字符,真的有很多种可能性。