C++ 如何使输出函数将格式化输出写入屏幕和输出文件
也许您可以传入一个ostream对象作为参数,然后用该参数的名称替换函数中出现的所有cout。然后可以运行该函数两次C++ 如何使输出函数将格式化输出写入屏幕和输出文件,c++,arrays,function,if-statement,iomanip,C++,Arrays,Function,If Statement,Iomanip,也许您可以传入一个ostream对象作为参数,然后用该参数的名称替换函数中出现的所有cout。然后可以运行该函数两次 Number of scores = 3 Lowest Score = 82 Highest Score = 92 Mean Score = 87 Name Score IsLowest IsHighest >=Mean F1 L1 82 Y N N F2 L2 87
Number of scores = 3
Lowest Score = 82
Highest Score = 92
Mean Score = 87
Name Score IsLowest IsHighest >=Mean
F1 L1 82 Y N N
F2 L2 87 N N Y
F3 L3 92 N Y Y
(或者将函数设置为调用自身,这样您就不必每次都输入cout)。
这个方法唯一的问题是,我看到您在函数内部捕获输入。如果你想使用上面的方法,你必须移动一些东西。相反,我将设置一个不同的函数,该函数将字符串作为输入,并将所述字符串同时插入cout和您的文件。因此,与其写
printReport(cout, other args);
printReport(outFile, other args);
cout通常,以下函数用于在文件中复制控制台输出
...
functionName("hi", outfile);
...
void functionName(string str, ostream outfile)
{
cout<<str;
outfile<<str;
}
控制台窗口格式也将保留在文本文件中
cout<<"hi";
file<<"hi";
...
functionName("hi", outfile);
...
void functionName(string str, ostream outfile)
{
cout<<str;
outfile<<str;
}
#include <stdarg.h> /* va_list, va_start, va_arg, va_end */
void print(FILE *f, char const *fmt, ...) {
va_list ap;
//Normal console print
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
//Printing to file
if (f != NULL) {
va_start(ap, fmt);
vfprintf(f, fmt, ap);
va_end(ap);
}
}
FILE *fp = fopen("logfile.txt","a");
print(fp, "%d\t%d\n, 1, 100);//logs the console output to logfile.txt