在C ++中将变量名转换为字符串 [英] converting a variable name to a string in C++

查看:223
本文介绍了在C ++中将变量名转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要将一些数据输出到文件。例如假设我有两个双精度向量:

I'd like to output some data to a file. For example assume I have two vectors of doubles:

vector<double> data1(10);
vector<double> data2(10); 

是一个简单的方法来输出到文件,使第一行包含标题'data1 '和'data2'后跟实际内容。
输出数据的函数将被传递各种不同的数组,所以硬编码标题的
是不可能的 - 理想情况下,我想将变量名称
转换为某个字符串,然后输出该字符串后面是矢量数组的内容。但是,我不知道如何将变量名称'data1'转换为一个字符串,
或者如果它可以很容易做到(从阅读论坛,我猜是不能)
如果这是不可能的替代方法可能是使用关联的
容器,如map或可能更简单的pair容器。

is there an easy way to output this to a file so that the first row contains the headings 'data1' and 'data2' followed by the actual contents. The function which outputs the data will be passed various different arrays so hardcoding the name of the heading is not possible - ideally I'd like to convert the variable name to some string and then output that string followed by the contents of the vector array. However, I'm not sure how to convert the variable name 'data1' to a string, or indeed if it can easily be done (from reading the forums my guess is it can't) If this is not possible an alternative might be to use an associative container such as map or perhaps more simply a 'pair' container.

pair<vector<double>,string> data1(10,'data1');  

欢迎任何建议。

推荐答案

您可以使用预处理器stringify执行所需操作:

You can use the preprocessor "stringify" # to do what you want:

#include <stdio.h>

#define PRINTER(name) printer(#name, (name))

void printer(char *name, int value) {
    printf("name: %s\tvalue: %d\n", name, value);
}

int main (int argc, char* argv[]) {
    int foo = 0;
    int bar = 1;

    PRINTER(foo);
    PRINTER(bar);

    return 0;
}


name: foo   value: 0
name: bar   value: 1

(对不起, printf ,我从来没有得到< iostream> ,但这应该足够了。)

(Sorry for printf, I never got the hang of <iostream>. But this should be enough.)

这篇关于在C ++中将变量名转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆