我想将同一行的两个 fprintf()
调用组合成一个函数调用,例如,fprintf_together_with_variable_name(FILE* fpheader, FILE* fpresult, char* f_str,. ..)
.
我的 MWE:
#include <stdio.h>
#define var2str(e) (#e)
int main() {
FILE* fpresult = fopen("result.txt", "a");
FILE* fpheader = fopen("header.txt", "w");
char* mtx = "web-Google.mtx";
double time = 3.452;
int flop = 7684;
fprintf(fpresult, "%s\t", mtx); fprintf(fpheader, "%s\t", var2str(mtx));
fprintf(fpresult, "%g\t", time); fprintf(fpheader, "%s\t", var2str(time));
fprintf(fpresult, "%d\t", flop); fprintf(fpheader, "%s\t", var2str(flop));
fprintf(fpresult, "\n"); fprintf(fpheader, "\n");
fclose(fpresult);
fclose(fpheader);
return 0;
}
很容易为每种类型int
、double
和char*
编写一个函数,或者将变量名作为字符串传递;然而,拥有一个只接受变量并处理所有类型的通用函数会很棒。
最佳答案
有点丑,但是你试过吗
#define var2str(e) e,#e
fprintf(fpresult, "%s\t%s\t", var2str(mtx));
甚至更丑:P
#define var2str(e) " %s\t", e,#e
fprintf(fpresult, "%s\t"var2str(mtx));
我认为这应该可行。
关于c - 在 C 中打印通用变量的名称和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18733042/