Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中打印泛型变量的名称和值_C_Generics_Pragma - Fatal编程技术网

在C中打印泛型变量的名称和值

在C中打印泛型变量的名称和值,c,generics,pragma,C,Generics,Pragma,我想将同一行上的两个fprintf()调用组合成一个函数调用,例如,fprintf\u与变量名(FILE*fpheader,FILE*fpresult,char*f\u str,…)一起调用 我的MWE: #include <stdio.h> #define var2str(e) (#e) int main() { FILE* fpresult = fopen("result.txt", "a"); FILE* fpheader = fopen("he

我想将同一行上的两个
fprintf()
调用组合成一个函数调用,例如,
fprintf\u与变量名(FILE*fpheader,FILE*fpresult,char*f\u 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;
}
#包括
#定义var2str(e)(#e)
int main(){
文件*fpresult=fopen(“result.txt”,“a”);
FILE*fpheader=fopen(“header.txt”、“w”);
char*mtx=“web Google.mtx”;
双倍时间=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);
返回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));

我想这应该行得通。

是的,它肯定会很棒。你可能可以用C11的(u Generic)和varargs宏来实现它。GoogleTest库使用宏来实现类似的结果,所以我认为这样做没有什么丢脸的。我想知道你是否可以进一步推广格式字符串,也许可以使用typeof(e)==int?“%d”:…@lee如果可以这样做,至少可以附加第二个%s,因为这始终是相同的。