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

查看:59
本文介绍了将变量名转换为 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' 转换为字符串,或者确实如果它可以轻松完成(从阅读论坛我猜它不能)如果这是不可能的,替代方法可能是使用关联容器,例如地图或更简单的配对"容器.

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	value: %d
", 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,我从来没有掌握 的窍门.但这应该足够了.)

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

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

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